'Merging an object to a list of objects [duplicate]
Hi all I’m trying to merge a object into each object inside an array something like this
Object to be inserted/merged:
Object1 : {‘name’:””}
The array of objects into which above needs to be merged
Array : [{‘dob’ : 22011991}, {‘class’ : 8208}]
And, the expected output:
[ {‘name’:””,’dob’ : 2201191}, {‘name’:””,‘class’ : 8208}]
Solution 1:[1]
const object1 = {name: ''};
const arr = [{ dob: 22011991 }, { class: 8208 }]
const merged = arr.map(item => ({ ...item, ...object1 }));
Solution 2:[2]
One possible solution by using .map and ... spread.
console.log(
[{dob : 22011991}, {class : 8208}]
.map(obj => ({
...obj,
...{ name : ""}
}))
);
Solution 3:[3]
Here is something similar, but if you just want to push one key from object1.
const object1 = {name: ''};
const arr = [{ dob: 22011991 }, { class: 8208}]
const merged = [];
for (let i = 0; i < arr.length; i++) {
const currentObjInArr = arr[i];
merged.push({...currentObjInArr, ...object1})
};
console.log('merged: ', merged);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | viveso |
| Solution 2 | jsN00b |
| Solution 3 | jsN00b |
