VUE学习笔记——es6对象合并 数组转对象
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.na...
·
测试数据
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);
更多推荐
已为社区贡献9条内容
所有评论(0)