Why can't I build this Javascript object?
- by Alex Mcp
I have an object I'm trying to populate from another object (that is, iterate over a return object to produce an object with only selected values from the original). My code looks like this:
var collect = {};
function getHistoricalData(username){
$.getJSON("http://url/" + username + ".json?params",
function(data){
for (var i=0; i < data.length; i++) {
console.log(i);
collect = { i : {text : data[i].text}};
$("#wrap").append("<span>" + data[i].text + "</span><br />");
};
console.log(collect);
});
}
So I'm using Firebug for debugging, and here's what I know:
The JSON object is intact
console.log(i); is showing the numbers 1-20 as expected
When I log the collect object at the end, it's structure is this:
var collect = { i : {text : "the last iteration's text"}};
So the incrementer is "applying" to the data[i].text and returning the text value, but it's not doing what I expected, which is create a new member of the collect object; it's just overwriting collect.i 20 times and leaving me with the last value.
Is there a different syntax I need to be using for assigning object members? I tried collect.i.text = and collect[i].text = and the error was that whatever I tried was undefined.
I'd love to know what's going on here, so the more in-depth an explanation the better.
Thanks!