Javascript 将属性添加到对象数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38922998/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add property to an array of objects
提问by Patrick
I have an array of objects as shown below
我有一个对象数组,如下所示
Object {Results:Array[2]}
Results:Array[2]
[0-1]
0:Object
id=1
name: "Rick"
1:Object
id=2
name:'david'
I want to add one more property named Active to each element of this array of Objects.
我想再向这个对象数组的每个元素添加一个名为 Active 的属性。
The final outcome should be as follows.
最终结果应该如下。
Object {Results:Array[2]}
Results:Array[2]
[0-1]
0:Object
id=1
name: "Rick"
Active: "false"
1:Object
id=2
name:'david'
Active: "false"
Can someone please let me know how to achieve this.
有人可以让我知道如何实现这一目标。
回答by sidonaldson
or use map
或使用 map
Results.map(obj=> ({ ...obj, Active: 'false' }))
Edited to reflect comment by @adrianolsk to not mutate the original and instead return a new object for each.
编辑以反映@adrianolsk 的评论,不改变原始对象,而是为每个对象返回一个新对象。
回答by Tholle
回答by Joel Balmer
I came up against this problem too, and in trying to solve it I kept crashing the chrome tab that was running my app. It looks like the spread operator for objectswas the culprit.
我也遇到了这个问题,在试图解决它的过程中,我一直在运行我的应用程序的 chrome 选项卡崩溃。看起来对象的扩展运算符是罪魁祸首。
With a little help from adrianolsk's comment and sidonaldson's answer above, I used Object.assign()the output of the spread operator from babel, like so:
在 adrianolsk 的评论和上面 sidonaldson 的回答的帮助下,我使用了Object.assign()来自 babel 的扩展运算符的输出,如下所示:
this.options.map(option => {
// New properties to be added
const newPropsObj = {
newkey1:value1,
newkey2:value2
};
// Assign new properties and return
return Object.assign(option, newPropsObj);
});
回答by Ivan De Jesus Quezada Segura
Object.defineProperty(Results, "Active", {value : 'true',
writable : true,
enumerable : true,
configurable : true});
回答by Arash MAS
It goes through the object as a key-value structure. Then it will add a new property named 'Active' and a sample value for this property ('Active) to every single object inside of this object. this code can be applied for both array of objects and object of objects.
它作为键值结构穿过对象。然后它将添加一个名为“Active”的新属性和此属性(“Active”)的示例值到此对象内的每个对象。此代码可应用于对象数组和对象对象。
Object.keys(Results).forEach(function (key){
Object.defineProperty(Results[key], "Active", { value: "the appropriate value"});
});