ES6 数组转对象

测试数据

let array = [
    {name: 'Conan', age: 17, gender: true}, 
    {name: 'Ran', age: 16}, 
    {name: 'Sherry', age: 20}
];

析构函数

let result = {...array};

/* 
    {
        0:{"name":"Conan","age":17,"gender":true},
        1:{"name":"Ran","age":16},
        2:{"name":"Sherry","age":20}}
    }
*/

累加器

let result = array.reduce((accumulator, current) => {
    accumulator[current.name] = current;
    return accumulator;
}, {});

/* 
    {
        Conan: {name: "Conan", age: 17, gender: true}
        Ran: {name: "Ran", age: 16}
        Sherry: {name: "Sherry", age: 20}
    }
*/

循环

let result = {};
array.forEach((item, index) => result[item.name] = item);
  • forEach
  • for...of
  • for
  • map
  • ...

你可能感兴趣的:(ES6 数组转对象)