Skip to content Skip to sidebar Skip to footer

Object.assign() And Array Of Objects

I have a nested array like this const names= [[{name: 'John'}, {name: 'Mary'}], [{name: 'Paul'}, {name: 'Peter'}]]; I would like inject country into the nested object

Solution 1:

You can use flat() to create a new array with all sub-array elements concatenated before using map() like the following way:

const names= [[{name: "John"}, {name: "Mary"}],
           [{name: "Paul"}, {name: "Peter"}]];
const country = {country :"USA"}
const combined = names.flat().map(p =>Object.assign(p, country));
console.log(combined);

Solution 2:

Make use of reduce to flatten your array along with map and object.assign to add the country value to each object

const names= [[{name: "John"}, {name: "Mary"}],
           [{name: "Paul"}, {name: "Peter"}]];
const country = {country :"USA"};
const newNames = names.reduce((acc, item) =>{
    acc= acc.concat(item.map(value =>Object.assign({}, value, country)));
    return acc;
},[]);
console.log(newNames);

Solution 3:

It's about using a nested map in an outer map:

const names = [
  [{
    name: "John"
  }, {
    name: "Mary"
  }],
  [{
    name: "Paul"
  }, {
    name: "Peter"
  }]
]

const country = { country: 'USA' }

const output = names.map (xs => xs.map (x => ({ ...x, ...country })))

console.log (output)

Solution 4:

You might declare a new array literal, list country as the first item, then spread the names[0] array into it, no need for Object.assign nor .map if you only have one sub-array:

const names= [[{name: "John"}, {name: "Mary"}],
           [{name: "Paul"}, {name: "Peter"}]];
const country = {country :"USA"};
const newNames = [[country, ...names[0]]];
console.log(newNames);

Solution 5:

You can double map the names array and it's nested array and destructure country into each item.

const names = [[{name: "John"}, {name: "Mary"}],
           [{name: "Paul"}, {name: "Peter"}]];
           
const country = {country :"USA"};

const namesWithCountry = names.map(name => name.map(n => ({...n, ...country})));

console.log(namesWithCountry);

Post a Comment for "Object.assign() And Array Of Objects"