javascript - JS reducer:返回组合的对象数组
问题描述
我有这样两个对象数组:
const first = [{text: 'sometext1', applicable: true}, {text: 'sometext2', applicable: false}, {text: 'sometext3', applicable: true}];
const second = [{text: 'sometext1', applicable: true}, {text: 'sometext2', applicable: true}];
结果我想得到这样的数组:
const result = [{text: 'sometext1', applicable: true}, {text: 'sometext2', applicable: true}, {text: 'sometext3', applicable: true}];
所以 => 只需将第一个数组中所有不存在的项目添加到第二个数组,并通过“文本”键过滤。
可以通过减速器来做吗?或者也许有更好的方法?
解决方案
只需遍历第一个数组并检查第二个数组中是否存在每个项目,如果不存在则推入第二个数组。
first.forEach((item) => {
const index = second.findIndex((st) => st.text === item.text);
if(index < 0) {
second.push(item);
}
})