简体   繁体   中英

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

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); 

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); 

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];
        }
    }
}

How about

let obj = {}

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

console.log(obj)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM