0

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};
}
4
  • 2
    You can always use .push(), but even as it stands, that should be good enough. What exactly isn't working here? BTW, shouldn't you check for i < obj.data.length instead? Commented Sep 29, 2015 at 19:36
  • Please consider adding a JSfiddle to show your current error. Commented Sep 29, 2015 at 19:38
  • is it data.length or obj.data.length ? Commented Sep 29, 2015 at 19:38
  • It's obj.data.length, my mistake... Please give the answer so i can vote. Thanks Commented Sep 29, 2015 at 19:42

2 Answers 2

1

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
}
Sign up to request clarification or add additional context in comments.

Comments

1

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});
}

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.