Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert array of objects into object of objects properties from array

I need to convert an array of objects into an object of objects properties from the array.

Here is an example of an array of objects

const array = [
 {
  book:5,
  car: 6,
  pc: 7
 },
 {
  headphone: 9,
  keyboard: 10
 },
];

I need it to be converted to

const obj = {
 book:5,
 car: 6,
 pc: 7,
 headphone: 9,
 keyboard: 10
};

I tried many ways but can't achieve the final result. Thanks in advance

like image 523
Artyom Amiryan Avatar asked Dec 06 '22 11:12

Artyom Amiryan


2 Answers

You could spread the array as parameters (spread syntax ...) for Object.assign, which returns a single object.

const
    array = [{ book: 5, car: 6, pc: 7 }, { headphone: 9, keyboard: 10 }],
    object = Object.assign({}, ...array);
    
console.log(object);
like image 169
Nina Scholz Avatar answered Jan 02 '23 04:01

Nina Scholz


You can use .reduce() and Object.assign() methods:

const array = [
  {book:5, car: 6, pc: 7},
  {headphone: 9, keyboard: 10},
];

const result = array.reduce((r, c) => Object.assign(r, c), {});

console.log(result);
like image 45
Mohammad Usman Avatar answered Jan 02 '23 04:01

Mohammad Usman