Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

I have a jQuery.each loop iterating through a JSON object that has three sets of data, but for some reason the loop outputs 13 objects instead of 3, and 10 of them are empty. Here is my code:

var teammates_info=[];
var teammate_json={"teammates":[{"id":"12","first_name":"Bob","last_name":"Johnson","user_img":"","status":"offline","new_messages":"0"},{"id":"9","first_name":"John","last_name":"Doe","user_img":"","status":"offline","new_messages":"0"},{"id":"10","first_name":"test","last_name":"test","user_img":"","status":"offline","new_messages":"0"}]};

jQuery.each(teammate_json.teammates,function(index,teammate){
    teammates_info[teammate.id]=[{"first_name":teammate.first_name,"last_name":teammate.last_name,"user_img":teammate.user_img,"status":teammate.status,"new_messages":teammate.new_messages}];
}); 

console.log(teammates_info.length); //outputs 13 not 3

If I do a document.write(teammates_info); I get ,,,,,,,,,[object Object],[object Object],,[object Object], so you can see all the empty array elements that are being created.

I am trying to output an array of objects, that way I can reference a teammate's data later in my code like teammates_info[12]["first_name"], but I am stumped as to why 13 array elements are created instead of just 3.

share|improve this question
1  
jsfiddle.net/7bZtV/3 Use push(), don't set your specific indexes for array. Otherwise, use an non indexed object, not an array – A. Wolff Sep 27 '13 at 11:09
    
@A.Wolff I need to set a specific index that way I can reference it by the teammate's ID later in the code. – BWDesign Sep 27 '13 at 11:10
    
Just edited my previous comment, so use an object, not an array – A. Wolff Sep 27 '13 at 11:10
    
Ok. I will give that a try. – BWDesign Sep 27 '13 at 11:11
2  
see: jsfiddle.net/7bZtV/5 – A. Wolff Sep 27 '13 at 11:12

1 Answer 1

up vote 1 down vote accepted

You should use non indexed object, not an array:

var teammates_info = {};

DEMO

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.