js数组中数据相同合并数据
方法一:
function mergeSimilarItems(arr) { return arr.reduce((acc, current) => { const existingItemIndex = acc.findIndex(item => item.name === current.name); if (existingItemIndex >= 0) { // 如果已存在相同id的项,则合并数据 acc[existingItemIndex].count += current.count; } else { // 如果不存在,直接添加到结果数组 acc.push({ ...current }); } return acc; }, []); }
// 示例数据 const items = [ { name: '张三', count: '团团'}, { name: '李四', count: '圆圆'}, { name: '张三', count: '恭喜'}, { name: '李四', count: '发财'} ]; // 使用函数 const mergedItems = mergeSimilarItems(items); console.log(mergedItems); // [
{name:'张三',count:'团团恭喜'},
{name:'李四',count:'圆圆发财'}
]
方法二:
function mergeSimilarItems(arr) { var afterData = []; arr.forEach(item => { let flag = afterData.find( item1 => item1.name=== item.name ); if (!flag) { afterData.push({ projectName: item.projectName, origin: [item] }); } else { flag.origin.push(item); } }); console.log("afterData", afterData); return afterData; } // 示例数据 const items = [ { name: '张三', count: '团团'}, { name: '李四', count: '圆圆'}, { name: '张三', count: '恭喜'}, { name: '李四', count: '发财'} ]; // 使用函数 const mergedItems = mergeSimilarItems(items) console.log(mergedItems); // [
{name:'张三',
orgin:[
{name:'张三',count:'团团'},
{name:'张三',count:'恭喜'}
]
},
{name:'李四',
orgin:[
{name:'李四',count:'圆圆'},
{name:'李四',count:'发财'}
]
}
]