0

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.

5
  • 1
    jsfiddle.net/7bZtV/3 Use push(), don't set your specific indexes for array. Otherwise, use an non indexed object, not an array Commented Sep 27, 2013 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. Commented Sep 27, 2013 at 11:10
  • Just edited my previous comment, so use an object, not an array Commented Sep 27, 2013 at 11:10
  • Ok. I will give that a try. Commented Sep 27, 2013 at 11:11
  • 2
    see: jsfiddle.net/7bZtV/5 Commented Sep 27, 2013 at 11:12

1 Answer 1

1

You should use non indexed object, not an array:

var teammates_info = {};

DEMO

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.