Why can't I create this Javascript object?

I have an object that I am trying to fill from another object (i.e. iterates over a return object to create an object with only selected values ​​from the original). My code is as follows:

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 use Firebug for debugging, and here is what I know:

  • JSON object is not corrupted
  • console.log(i); shows numbers 1-20 as expected
  • When I register an object collectat the end, it looks like this: var collect = { i : {text : "the last iteration text"}};

    Thus, the increment "applies" to the [i] .text data and returns the text value, but does not fulfill what I expected, creating a new member of the collection object; it just overwrites collect.i20 times and leaves me with the last value.

, ? collect.i.text = collect[i].text =, , , , undefined.

, , .

!

+3
3

, , , - .

collect = { i : {text : data[i].text}};

: , i, , text collect. collect i, i - .

, , , : collect[i]. , , . ( , ):

collect[i] = { text: data[i]["text"] };

+2
 collect[i] = {text : data[i].text};

collect[i].text, collect[i] , undefined, text.

:

  • collect.i collect["i"]. collect[i].
  • .push.
0

As you already know, the problem is in this line:

 collect = { i : {text : data[i].text}};

Each iteration of the loop, you delete the collection object and assign it a new object as a value. That is why, in the end, it shows only the last iteration.

Try the following:

 collect[i] = {text : data[i].text};
0
source

Source: https://habr.com/ru/post/1736767/


All Articles