3 回答

TA貢獻(xiàn)1845條經(jīng)驗(yàn) 獲得超8個(gè)贊
您可以使用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貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超4個(gè)贊
使用reduce和Object.assign合并數(shù)組中的項(xiàng)目:
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)));
添加回答
舉報(bào)