let arr = [{ a: "xinxin" },{ a: "pipi" },{ a: "zhazha" },{ a: "xinxin", c: 1 } ];使用reduce实现合并相同的key
时间: 2023-09-21 20:11:42 浏览: 65
C.rar_site:www.pudn.com
const result = arr.reduce((acc, cur) => {
const foundIndex = acc.findIndex(item => item.a === cur.a);
if (foundIndex !== -1) {
acc[foundIndex] = { ...acc[foundIndex], ...cur };
} else {
acc.push(cur);
}
return acc;
}, []);
console.log(result); // [{ a: "xinxin", c: 1 }, { a: "pipi" }, { a: "zhazha" }]
阅读全文