需求:一个数组对象,里面有重复的数据,需要合并在一起
数组对象为
const items = [
{ id: 1, type: "fruit", name: "apple", color: "red" },
{ id: 2, type: "vegetable", name: "carrot", color: "orange" },
{ id: 1, type: "fruit", name: "apple2", size: "medium" },
{ id: 3, type: "fruit", name: "banana", color: "yellow" },
];
从数据可以看出来,id为1的数据有两个,type也相等,把他组合在一起得到
使用reduce累加的方式
const items = [
{ id: 1, type: "fruit", name: "apple", color: "red" },
{ id: 2, type: "vegetable", name: "carrot", color: "orange" },
{ id: 1, type: "fruit", name: "apple2", size: "medium" },
{ id: 3, type: "fruit", name: "banana", color: "yellow" },
];
interface Item {
id: number;
type: string;
name: string;
color?: string;
size?: string;
}
function mergeObject(items: Item[]) {
const result = items.reduce((acc, item) => {
const key: string = `${item.id}-${item.type}`;
if (acc[key]) {
acc[key] = { ...acc[key], ...item };
} else {
acc[key] = item;
}
return acc;
}, {});
console.log(result);
return Object.values(result);
}
console.log("----------------", mergeObject(items));
结果:
- (3) [{…}, {…}, {…}]
- 0: {id: 1, type: 'fruit', name: 'apple2', color: 'red', size: 'medium'}
- 1: {id: 2, type: 'vegetable', name: 'carrot', color: 'orange'}
- 2: {id: 3, type: 'fruit', name: 'banana', color: 'yellow'}

1761

被折叠的 条评论
为什么被折叠?



