4

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

Rarblack
  • 4,559
  • 4
  • 22
  • 33
Artyom Amiryan
  • 2,846
  • 1
  • 10
  • 22
  • These type of questions attract people that almost code golf the answer without giving you any explanation on what they did. Granted, you'll be back in 2 days with a new request. – nicholaswmin Oct 16 '18 at 16:37
  • 1
    `const obj = Object.assign({}, ...array)` is likely the cleanest. The spread operator will do the job here, and Object.assign does exactly what you need. – briosheje Oct 16 '18 at 16:42
  • @nicholaswmin as you can see, 2 years already passed, and you can see that I'm not back with another request related to this, so stop making wrong assumptions – Artyom Amiryan Sep 15 '20 at 16:37

4 Answers4

14

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
3

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);
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
0

You can also loop through the array using for loops. Using .reduce() and Object.assign() may not me that clear to understang what is happening for people that don't understand too much about Objects in js, but is definitively less code.

for(let i = 0; i < array.length; i++){
    for (let key in array[i]) {
        if (array[i].hasOwnProperty(key)) {
            obj[key] = array[i][key];
        }
    }
}
Vencovsky
  • 28,550
  • 17
  • 109
  • 176
-1

How about

let obj = {}

for(let object of array) {
  Object.assign(obj, object)
}

console.log(obj)
Umair Abid
  • 1,453
  • 2
  • 18
  • 35