Faryal Imam
Faryal Imam

Reputation: 83

How to dynamically add an attribute to JSON array

I have this JSON array

{"nodes":[
        {"type":"simple-node","left":500,"id":"node-start","content":"Start"},
        {"type":"simple-node","left":500,"id":"node-1","content":"Ironing"},
        {"type":"simple-node","left":500,"id":"node-end""content":"End"}
         ],

"connections":[
        {"start":"node-start","end":"node-1"},
        {"start":"node-4","end":"node-5"}
              ]
}

I need to dynamically add "top" attribute to each element in nodes array so that it may look like this

{"nodes":[
        {"type":"simple-node","left":500,"top":3403.252685546875,"id":"node-start","content":"Start"},
        {"type":"simple-node","left":500,"top":3703.252685546875,"id":"node-1","content":"Ironing"},
        {"type":"simple-node","left":500,"top":3903.252685546875,"id":"node-end""content":"End"}
         ],

"connections":[
        {"start":"node-start","end":"node-1"},
        {"start":"node-4","end":"node-5"}
              ]

Upvotes: 1

Views: 83

Answers (2)

Nenad Vracar
Nenad Vracar

Reputation: 122087

You can use forEach on obj.nodes and add object property

var obj = {"nodes":[{"type":"simple-node","left":500,"id":"node-start","content":"Start"},{"type":"simple-node","left":500,"id":"node-1","content":"Ironing"},{"type":"simple-node","left":500,"id":"node-end","content":"End"}],"connections":[{"start":"node-start","end":"node-1"},{"start":"node-4","end":"node-5"}]}

obj.nodes.forEach((e) => {
  e.top = 3403.252685546875;
});

console.log(obj)

Update: First you need to turn your json string to object with JSON.parse(yourjson) if you didn't.

Upvotes: 1

sferret
sferret

Reputation: 461

    var obj={"nodes":[
       {"type":"simple-node","left":500,"id":"node-start","content":"Start"},
       {"type":"simple-node","left":500,"id":"node-1","content":"Ironing"},
       {"type":"simple-node","left":500,"id":"node-end""content":"End"}
     ]};
      var top_array=[2495,4985,3467];
      for(i=0;i<obj.nodes.length;i++){
          obj.nodes[i].top=top_array[i];
       }

In case you need to copy the keys from an array

Upvotes: 0

Related Questions