简体   繁体   English

如何将新的键值插入到现有的 JSON 对象数组中?

[英]How to insert a new key value to the existing JSON object array?

I have the below JSON array,我有以下 JSON 数组,

const data = [{id:1,name:'a'},{id:2,name:'b'},{id:3,name:'c'}]

and I have to insert one more property to each object, and expected result would be like this.并且我必须向每个对象再插入一个属性,预期结果将是这样的。

const data = [{id:1,name:'a',selected:false},{id:2,name:'b',selected:false},{id:3,name:'c',selected:false}]

I'm trying to achieve this javascript only.我只想实现这个javascript。

Please help me on this.请帮我解决这个问题。

The question did not reach the standards of Stackoverflow, but from your comments, I believe that you are seriously looking for a solution's than your reputation.这个问题没有达到 Stackoverflow 的标准,但是从您的评论中,我相信您正在认真寻找解决方案而不是您的声誉。

The answer is kind of simple old-school method, please refer and give a try.答案是一种简单的老派方法,请参考并尝试。 Thanks.谢谢。

 const data = [{id:1,name:'a',selected:false},{id:2,name:'b',selected:false},{id:3,name:'c',selected:false}] data.forEach((element,index) => { element["selected"] = false, element["test"]=index+1 // any key-value pairs }); console.log(data)

A simple loop is all you need.一个简单的循环就是你所需要的。

for (let item of data) {
  item.selected = false;
}

On each iteration of this loop, item becomes the next item from the iterated object ( data , in this case).在此循环的每次迭代中, item成为迭代对象(在本例中为data )的下一个项目。 Since the array still references these same objects, you can modify item , and this modification also appears on the item in data ... again because it is the same object.由于数组仍然引用这些相同的对象,因此您可以修改item ,并且此修改也出现在data的 item 上...再次因为它是同一个对象。

var data = [{id:1,name:'a'},{id:2,name:'b'},{id:3,name:'c'}];

for (i = 0; i < data.length; i++) { 
   // add the addition property using dot notation
   data[i].selected = 'false';
}

// output to console the updated data
   console.log(data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM