3 回答
TA贡献1845条经验 获得超8个赞
您可以使用reduce()和findIndex()
let data = [
{"Name" : "Arrow",
"Year" : "2001"
},
{"Name" : "Arrow",
"Type" : "Action-Drama"
},
{ "Name" : "GOT",
"Type" : "Action-Drama"
}
]
let res = data.reduce((ac,a) => {
let ind = ac.findIndex(x => x.Name === a.Name);
ind === -1 ? ac.push({...a}) : ac[ind] = {...ac[ind],...a};
return ac;
},[])
console.log(res)
TA贡献1796条经验 获得超4个赞
使用reduce和Object.assign合并数组中的项目:
const data = [{
"Name" : "Arrow",
"Year" : "2001"
}, {
"Name" : "Arrow",
"Type" : "Action-Drama"
}, {
"Name" : "GOT",
"Type" : "Action-Drama"
}];
function mergeByProp (prop, xs) {
return xs.reduce((acc, x) => {
if (!acc[x[prop]]) {
acc[x[prop]] = x;
} else {
acc[x[prop]] = Object.assign(acc[x[prop]], x);
}
return acc;
}, {});
}
function objToArr (obj) {
return Object.keys(obj).map(key => obj[key]);
}
console.log(objToArr(mergeByProp('Name', data)));
添加回答
举报