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;
}, {});