我有这样两个对象数组:
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}];
so => 只需将第一个数组中所有不存在的项目添加到第二个数组,并按“text”键过滤。
可以通过reducer来实现吗?或者也许有更好的方法?
最佳答案
只需迭代第一个数组并检查第二个数组中是否存在每个项目,如果不存在则插入第二个数组。
first.forEach((item) => {
const index = second.findIndex((st) => st.text === item.text);
if(index < 0) {
second.push(item);
}
})
关于javascript - JS reducer : return combined array of objects,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54401098/