0

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
2
  • what do you mean by "view the object"? Do you mean how can you perform alert with its properties? Commented Oct 7, 2011 at 11:54
  • yes, access its properties :) Commented Oct 7, 2011 at 11:55

2 Answers 2

1

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

Comments

1
- 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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.