简体   繁体   中英

Add new key:value pairs to existing an existing array

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).

nodes.forEach(function(n) {n.cx = n.i * 2});
for(var i=0; i<nodes.lenght;i++)
    nodes[i].cx = i*2;

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