简体   繁体   中英

Javascript add values to object dynamically

Let's supose i have something like this:

$scope.playersData =   [{
    "label": obj.data[0].player,
    "color": colors[0],
    "data": obj.data[0].value
}, {
    "label": obj.data[1].player,
    "color": colors[1],
    "data": obj.data[1].value
}];

This works if i have always only 2 items in obj.data.

Now, if i want to add values dynamically in a For Loop, how do i do it?

I tried something like this, not working:

var temparray = [];
for (var i = 0; i < data.length; i++) { 
    temparray[i] = {"label": obj.data[i].player,"color": colors[i],"data": obj.data[i].value};
}

Can you try this?

var temparray = [];
for (var i = 0; i < data.length; i++) { 
    var item = {"label": obj.data[i].player,"color": colors[i],"data": obj.data[i].value};
    temparray.push(item);  //. <---added
}

There is one mistake: replace from data.length to obj.data.length .

Also, you can use push for adding element to array.

var temparray = [];
for (var i = 0; i < obj.data.length; i++) { 
    temparray.push({"label": obj.data[i].player,"color": colors[i],"data": obj.data[i].value});
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM