简体   繁体   中英

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.

I tried to create the new key inside map function, but it only works with non-object variables.

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 :

 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() . 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.

 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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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