简体   繁体   English

将键值(对象)对添加到数组中的所有对象

[英]Add key value (object) pair to all objects in array

My question is related to Add key value pair to all objects in array 我的问题与将键值对添加到数组中的所有对象有关

However, the solutions don't work when I try to assign an object instead of a string, int etc. 但是,当我尝试分配对象而不是字符串,int等时,解决方案不起作用。

I tried to create the new key inside map function, but it only works with non-object variables. 我试图在map函数中创建新的键,但是它仅适用于非对象变量。

This works 这有效

arrObjects.map(item => item.newKey = 'xxx')

This doesn't 这不是

var obj = { a: 'a', b: 'b', c: 'c' }
arrObjects.map(item => item.newKey = obj)

Output: 输出:

 var arrOfObj = [{ name: 'eve' }, { name: 'john' }, { name: 'jane' }]; var obj = { a: 'a', b: 'b', c: 'c' } arrOfObj.map(item => item.newKey = obj); console.log(arrOfObj); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

You need to use ... (spread operator) 您需要使用... (扩展运算符)

 var arrOfObj = [{ name: 'eve' }, { name: 'john' }, { name: 'jane' }]; var obj = { a: 'a', b: 'b', c: 'c' }; arrOfObj.forEach(item => item.newKey = {...obj}); console.log(arrOfObj); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

Alternatively, use JSON : 或者,使用JSON

 var arrOfObj = [{ name: 'eve' }, { name: 'john' }, { name: 'jane' }]; var obj = { a: 'a', b: 'b', c: 'c' }; arrOfObj.forEach(item => item.newKey = JSON.parse(JSON.stringify(obj))); console.log(arrOfObj); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

You need to create a copy of object. 您需要创建对象的副本。 By default object is assigned as reference. 默认情况下,对象被分配为参考。 here ... is used to create a shallow copy 这里...用于创建浅表副本

 var arrOfObj = [{name: 'eve'}, {name: 'john'}, { name: 'jane'}]; var obj = { a: 'a', b: 'b', c: 'c'} arrOfObj.forEach(item => (item.newKey = {...obj})); console.log(arrOfObj); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

You can see some of use case here 您可以在这里看到一些用例

One alternative is to use Object.assign() . 一种替代方法是使用Object.assign() Remenber that objects are copied by the value of the reference, that was your problem, instead of a new object for every newKey , you had multiple references to the same object. 请记住,对象是通过引用的值复制的,这就是您的问题,而不是每个newKey都有一个新对象,您对同一个对象有多个引用。

 var arrOfObj = [ {name: 'eve'}, {name: 'john'}, {name: 'jane'} ]; var obj = { a: 'a', b: 'b', c: 'c' }; arrOfObj.map(item => item.newKey = Object.assign({}, obj)); console.log(arrOfObj); // After some modification. arrOfObj[0].newKey.a = "XXX" console.log(arrOfObj); 

You have to clone the item, you are adding the same object to multiple property. 您必须克隆该项目,将同一对象添加到多个属性。

See below how it should be. 请参阅下面的内容。

 var arrOfObj = [{ name: 'eve' }, { name: 'john' }, { name: 'jane' }]; var obj = { a: "a", b: "b", c: "c" } arrOfObj.map(item => // clone the item item.newKey = JSON.parse(JSON.stringify(obj)) ); console.log(arrOfObj); 

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

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