Im having some issues creating an array of objects in javascript
Please see my code below and tell me where im going wrong..
I simply want to loop through and access the values
<!-- Read XML Script -->
<script type="text/javascript">
// Object array
var myArray = [];
$(document).ready(function () {
$.ajax({
type: "GET",
url: "HighScore.xml",
dataType: "xml",
success: function (xml) {
$(xml).find('challenger').each(function () {
var name = $(this).find('Name').text();
var watts = $(this).find('Watts').text();
var Mins = $(this).find('Mins').text();
// objects in the array
challenger = new Object();
challenger.name = name;
challenger.watts = watts;
challenger.Mins = Mins;
myArray.push(challenger);
});
// look into the array
for (obj in myArray) {
// do i need to cast ?? how can i view the object ??
alert(obj + " - ");
}
},
error: function () {
alert("error");
}
});
});
</script>
asked Oct 7, 2011 at 11:51
JGilmartin
9,38814 gold badges72 silver badges91 bronze badges
2 Answers 2
The for .. in .. works different in javascript than in some other languages. Instead of the object, you will get the key. In your array therefore you'll get the index.
For iterating over arrays, just use an index-based array to avoid hassle:
for (var ix = 0; ix < myArray.length; ix++) {
var obj = myArray[ix];
alert(obj.name);
}
If you really want to use the for .. in .. syntax, use this:
var a = ['jan', 'klaas'];
for(var key in a) {
if (a.hasOwnProperty(key)) {
console.log(a[key].name);
}
}
answered Oct 7, 2011 at 11:55
Jan Jongboom
27.5k10 gold badges85 silver badges121 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
- for (obj in myArray) {
- // do i need to cast ?? how can i view the object ??
- alert(obj + " - ");
- }
+ for (var i = 0; i < myArray.length; i++) {
+ var obj = myArray[i];
+ // do i need to cast ?? how can i view the object ??
+ alert(JSON.stringify(obj, null, ' '));
+ }
answered Oct 7, 2011 at 11:55
4esn0k
10.6k7 gold badges38 silver badges40 bronze badges
Comments
lang-js
alertwith its properties?