Angular中实现对象数组的过滤与合并方法求助
嘿,我懂你要做的事儿——把数组里相同name的对象合并,把它们的items数组整合到一块儿对吧?你之前尝试用map()和filter()没成功,其实这俩方法确实能实现,不过可能需要搭配点额外的步骤;另外用reduce()会更简洁高效,我给你两种方案参考:
方案一:使用
Array.reduce()(推荐,更高效) 这种方法用reduce()构建一个临时对象,跟踪每个name对应的合并结果,最后再转成数组,时间复杂度是O(n),比多次遍历数组更高效:
function myFunction(arrayBefore) { // 用reduce构建一个以name为键的临时对象 const mergedObj = arrayBefore.reduce((accumulator, currentObj) => { // 如果当前name已经在临时对象里,就合并items数组 if (accumulator[currentObj.name]) { accumulator[currentObj.name].items = [ ...accumulator[currentObj.name].items, ...currentObj.items ]; } else { // 否则把当前对象浅拷贝后存入临时对象(避免修改原数组对象) accumulator[currentObj.name] = { ...currentObj }; } return accumulator; }, {}); // 把临时对象的值转成数组,就是最终结果 return Object.values(mergedObj); }
方案二:用
map() + filter()实现(贴合你之前的尝试) 如果你更想坚持用map()和filter(),可以先提取所有唯一的name,再针对每个name筛选出对应对象并合并items:
function myFunction(arrayBefore) { // 先获取所有不重复的name列表 const uniqueNames = [...new Set(arrayBefore.map(item => item.name))]; // 遍历每个唯一name,构建合并后的对象 return uniqueNames.map(name => { // 筛选出所有name匹配的对象 const matchedObjects = arrayBefore.filter(item => item.name === name); // 把所有匹配对象的items数组合并成一个数组 const combinedItems = matchedObjects.flatMap(obj => obj.items); // 返回新的合并对象 return { name, items: combinedItems }; }); }
测试示例
你可以用下面的代码验证效果:
const arrayBefore = [{name:'n1', items: ['i1']}, {name:'n2', items: ['i2']}, {name:'n1', items: ['i3']}]; console.log(myFunction(arrayBefore)); // 输出结果:[{name:'n1', items: ['i1','i3']}, {name:'n2', items: ['i2']}]
之前你用map()和filter()没成功,大概率是没先提取唯一的name列表,或者合并items的时候没把数组展开——比如直接把多个items数组放到一个数组里,而不是合并成一维数组,用flatMap()或者concat(...arrays)就能解决这个问题。
内容的提问来源于stack exchange,提问作者Niels Ferguson
相关产品推荐
相关产品推荐

