VUE学习笔记——es6对象合并 数组转对象

测试数据

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

方法一:循环

const arr = [{date: "2018-11-18", name: "demo1"}, {date: "2018-11-19", name: "demo2"}];
         const target = {};
      arr.forEach(a => {
        const source = JSON.parse(`{"${a.date}":"${a.name}"}`);//利用JSON.parse将对象
                                                              //格式直接造出来
        Object.assign(target,source);
      })
     // console.log(target)

方法二:析构函数

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

 

发布了68 篇原创文章 · 获赞 91 · 访问量 96万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览