js合并数组中的多个key相同的map## 标题js 合并数组中的map
function mergeMapsByKey(array, key) {
return array.reduce((accumulator, current) => {
const existingItem = accumulator.find(item => item[key] === current[key]);
if (existingItem) {
// 合并对象
Object.assign(existingItem, current);
} else {
// 添加新对象
accumulator.push(current);
}
return accumulator;
}, []);
}
// 示例数据
const maps = [
{ name: ‘Alice’, age: 25, city: ‘New York’ },
{ name: ‘Bob’, age: 30, city: ‘Paris’ },
{ name: ‘Alice’, age: 28, country: ‘USA’ },
{ name: ‘Charlie’, age: 22, city: ‘London’ }
];
// 使用key ‘name’ 合并
const mergedMaps = mergeMapsByKey(maps, ‘name’);
console.log(mergedMaps);