0

Here's my existing data:

var nodes = [
    {i: 0, radius: 18.637872483796723},
    {i: 0, radius: 17.174333481950903},
    {i: 0, radius: 13.194447610161163},
    {i: 1, radius: 8.000718059188364},
    {i: 1, radius: 4.08204211857112}
  ];

I need to add one new key:value pairs for each item in the list. It is dynamically calculated:

cx: i*2

So the new array would look like this:

[
  {i: 0, radius: 18.637872483796723, cx: 0},
  {i: 0, radius: 17.174333481950903, cx: 0},
  {i: 0, radius: 13.194447610161163, cx: 0},
  {i: 1, radius: 8.000718059188364, cx: 2},
  {i: 1, radius: 4.08204211857112, cx: 2}
];

I am a beginner, so excuse any terminology that I've butchered (I'm not sure if I'm using the term array correctly).

mdaniels
  • 99
  • 1
  • 9

2 Answers2

1
nodes.forEach(function(n) {n.cx = n.i * 2});
cybersam
  • 63,203
  • 6
  • 53
  • 76
  • For support in browsers made when the wooly mammoths were wandering the earth, there's always [`$.each`](https://api.jquery.com/jQuery.each/) from [jQuery](http://jquery.com/) and a similar thing in Underscore. – tadman Apr 03 '14 at 03:00
-1
for(var i=0; i<nodes.lenght;i++)
    nodes[i].cx = i*2;
Maneesh Singh
  • 555
  • 2
  • 12
  • yes nodes var is define in question . var nodes = [ {i: 0, radius: 18.637872483796723}, {i: 0, radius: 17.174333481950903}, {i: 0, radius: 13.194447610161163}, {i: 1, radius: 8.000718059188364}, {i: 1, radius: 4.08204211857112} ]; – Maneesh Singh Apr 03 '14 at 03:01
  • http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea – adeneo Apr 03 '14 at 03:03