给定两个数组:
const inputOne = [
{id: "valueA", prop: 123},
{id: "valueB", prop: 456}
]
const inputTwo = [
{id: "valueA", other: 54},
{id: "valueB", other: 98},
{id: "valueC", other: 11}
]
我正在尝试根据 inputOne
的 id
过滤 inputTwo
,然后合并在两者中找到的属性。
期望的输出:
combinedAndFiltered = [
{id: "valueA", other: 54, prop: 123},
{id: "valueB", other: 98, prop: 456}
]
我尝试过map
、filter
和/或reduce
的各种组合,但不知何故无法理解它。
最佳答案
此解决方案假设只有两个集合,并且每个集合中的 id
属性是唯一的。
您可以通过以下方式基于公共(public)属性 (id
) 创建两组合并对象的 an intersection:
- 迭代第一个集合,然后在第二个集合中搜索第一个集合的当前元素。
- 如果找到匹配项,则将两个对象组合成一个新对象,然后将该对象添加到累加器集中。
- 返回累加器
此方法返回一个新集合,其中包含在两个集合中找到的合并对象。如果任一集合中缺少某个对象,则该对象将不会包含在输出中。
const inputOne = [ {id: "valueA", prop: 123}, {id: "valueB", prop: 456}, {id: "valueD", prop: 789} ]
const inputTwo = [ {id: "valueA", other: 54}, {id: "valueB", other: 98}, {id: "valueC", other: 11} ]
function intersectAndMerge(a, b) {
const accumulator = []
for(let { id, ...props } of a) {
const match = b.find(e => e.id === id)
if(match !== undefined) {
accumulator.push({ ...match, ...props })
}
}
return accumulator
}
console.log(intersectAndMerge(inputOne, inputTwo))
这也可以通过reduce循环来完成,但我发现它的可读性较差:
const inputOne = [ {id: "valueA", prop: 123}, {id: "valueB", prop: 456}, {id: "valueD", prop: 789} ]
const inputTwo = [ {id: "valueA", other: 54}, {id: "valueB", other: 98}, {id: "valueC", other: 11} ]
function intersectAndMerge(a, b) {
return a.reduce((accumulator, { id, ...props }) => {
const match = b.find(e => e.id === id)
if(match !== undefined) {
accumulator.push({ ...match, ...props })
}
return accumulator
}, [])
}
console.log(intersectAndMerge(inputOne, inputTwo))
关于javascript - 基于另一个数组并组合过滤数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54014075/