根据条件合并两个对象数组并集



我正在尝试根据每个集合上的一些条件合并两组对象数组。如果在array2上没有找到array1上的keyword,则从array1中添加对象并添加属性值对number: 0,如果找到则将array1的属性添加到array2对象

这是我得到的距离,但一直在重复这些对象。

const array1 = [
{ keyword: 'present', prop: 'foo' },
{ keyword: 'another present', prop: 'bla' },
{ keyword: 'not present', prop: 'hey' }
]
const array2 = [
{ keyword: 'present', number: 12345 },
{ keyword: 'another present', number: 12345 }
]
const res = array1.reduce((acc, obj1) => {
for (const obj2 of array2) {
if (obj2.keyword === obj1.keyword) {
acc.push({
...obj1,
...obj2
})
} else {
acc.push({
...obj1,
number: 0
})
}
}
return acc
}, [])
console.log(res)
.as-console-wrapper { max-height: 100% !important; top: 0; }

这是期望的输出

[
{ keyword: 'present', prop: 'foo', number: 12345 },
{ keyword: 'another present', prop: 'bla', number: 12345 },
{ keyword: 'not present', prop: 'hey', number: 0 }
]

只要找到一个匹配项,就需要尽早中断循环。

const res = array1.reduce((acc, obj1) => {
for (const obj2 of array2) {
if (obj2.keyword === obj1.keyword) {
acc.push({
...obj1,
...obj2
})
return acc // as soon as obj2 is found, stop processing for obj1
}
}
acc.push({
...obj1,
number: 0
}) // if nothing from array2 is found
return acc
}, [])

最新更新