convert array of objects into object of objects properties from array

前端 未结 4 1848
名媛妹妹
名媛妹妹 2021-01-19 13:01

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

co         


        
相关标签:
4条回答
  • 2021-01-19 13:09

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

    0 讨论(0)
  • 2021-01-19 13:10

    How about

    let obj = {}
    
    for(let object of array) {
      Object.assign(obj, object)
    }
    
    console.log(obj)
    
    0 讨论(0)
  • 2021-01-19 13:14

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

    0 讨论(0)
  • 2021-01-19 13:19

    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];
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题