0

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}]
jsN00b
  • 3,584
  • 2
  • 8
  • 21

3 Answers3

0
const object1 = {name: ''};
const arr = [{ dob: 22011991 }, { class: 8208 }]
const merged = arr.map(item => ({ ...item, ...object1 }));
viveso
  • 49
  • 5
0

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);
jsN00b
  • 3,584
  • 2
  • 8
  • 21
Stigson
  • 21
  • 1
  • 2
  • Kindly ensure that the code snippet works. The above answer has been edited to fix issues and now it generates the expected result. – jsN00b Apr 13 '22 at 16:38
0

One possible solution by using .map and ... spread.

console.log(
  [{dob : 22011991}, {class : 8208}]
  .map(obj => ({
    ...obj,
    ...{ name : ""}
  }))
);
jsN00b
  • 3,584
  • 2
  • 8
  • 21