如何动态地将属性添加到JSON数组

时间:2016-05-18 16:59:46

标签: javascript json

我有这个JSON数组

{"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"}
              ]
}

我需要动态添加" top"属性到nodes数组中的每个元素,以便它看起来像这样

{"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"}
              ]

2 个答案:

答案 0 :(得分:1)

您可以在forEach上使用obj.nodes并添加对象属性

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)

更新:首先,如果不这样做,你需要将你的json字符串转换为JSON.parse(yourjson)对象。

答案 1 :(得分:0)

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

如果您需要从数组中复制键