如何对比多层嵌套对象数组 按Key匹配筛选Value一致的条目
嵌套对象数组匹配筛选方案
需求说明
给定两个结构相同的嵌套对象数组,先按顶层Key字段匹配对应分组,再对同一分组下的子项数组,筛选出两个数组中Key和Value均完全一致的子项,最终输出仅保留匹配项的结果数组。
输入数据
arr1 结构
arr1 =[ { "Key": "Exterior", "Value": [ { "Key": "Wheel Covers", "Value": "Center Cap" }, { "Key": "Body Coloured Bumpers", "Value": "-" }, { "Key": "Body Coloured Outside Door Handles ", "Value": "yes" }, { "Key": "Body Side Molding", "Value": "-" }, { "Key": "High-Mounted Stop Lamp", "Value": "yes" } ] }, { "Key": "Interiors", "Value": [ { "Key": "Seat Upholstery", "Value": "Vinyl" }, { "Key": "B & C Pillar Upper Trims", "Value": "-" }, { "Key": "C Pillar Lower Trim (Molded)", "Value": "yes" }, { "Key": "Dual-tone Interiors", "Value": "yes" }, { "Key": "Silver Accent Inside Door Handles", "Value": "-" }, { "Key": "Silver Accent on Center Garnish", "Value": "-" }, { "Key": "Silver Accent on Louvers", "Value": "-" }, { "Key": "Silver Accent on Steering Wheel", "Value": "-" } ] } ]
arr2 结构
arr2 =[ { "Key": "Exterior", "Value": [ { "Key": "Wheel Covers", "Value": "Full" }, { "Key": "Body Coloured Bumpers", "Value": "yes" }, { "Key": "Body Coloured Outside Door Handles ", "Value": "yes" }, { "Key": "Body Side Molding", "Value": "-" } ] }, { "Key": "Interiors", "Value": [ { "Key": "Seat Upholstery", "Value": "Fabric+Vinyl" }, { "Key": "B & C Pillar Upper Trims", "Value": "yes" }, { "Key": "C Pillar Lower Trim (Molded)", "Value": "yes" }, { "Key": "Dual-tone Interiors", "Value": "yes" }, { "Key": "Silver Accent Inside Door Handles", "Value": "yes" }, { "Key": "Silver Accent on Center Garnish", "Value": "-" }, { "Key": "Silver Accent on Louvers", "Value": "yes" }, { "Key": "Silver Accent on Steering Wheel", "Value": "yes" } ] } ]
实现代码(JavaScript)
先将其中一个数组转换为便于快速查找的映射结构,减少嵌套循环次数,提升匹配效率:
// 转换数组为「顶层Key -> 子项Key+Value集合」的映射 function buildLookupMap(arr) { const map = {} arr.forEach(group => { map[group.Key] = new Set( group.Value.map(item => `${item.Key}###${item.Value}`) ) }) return map } // 筛选匹配项 function getMatchedResult(arr1, arr2) { const lookupMap = buildLookupMap(arr2) return arr1.reduce((res, currentGroup) => { const groupKey = currentGroup.Key // 顶层Key不匹配则跳过该分组 if (!lookupMap[groupKey]) return res // 筛选子项中Key和Value均一致的条目 const matchedItems = currentGroup.Value.filter(item => { return lookupMap[groupKey].has(`${item.Key}###${item.Value}`) }) // 仅保留有匹配子项的分组 if (matchedItems.length) { res.push({ Key: groupKey, Value: matchedItems }) } return res }, []) } // 调用示例 const result = getMatchedResult(arr1, arr2) console.log(result)
输出结果
注:你提供的预期输出中「Interior」为笔误,实际匹配结果顶层Key与输入保持一致为「Interiors」
[ { "Key": "Exterior", "Value": [ { "Key": "Body Coloured Outside Door Handles ", "Value": "yes" }, { "Key": "Body Side Molding", "Value": "-" } ] }, { "Key": "Interiors", "Value": [ { "Key": "C Pillar Lower Trim (Molded)", "Value": "yes" }, { "Key": "Dual-tone Interiors", "Value": "yes" }, { "Key": "Silver Accent on Center Garnish", "Value": "-" } ] } ]
内容的提问来源于stack exchange,提问作者ltech
相关产品推荐
相关产品推荐

