我有两个数组
let a1 = [{id: 1, name: "terror"}, {id: 2, name: "comics"}, {id: 3, name: "suspense"}]
let a2 = [{id: 1, name: "terror"}, {id: 3, name: "suspense"}]
我需要将这些数组相互比较,得出如下结果:{id: 1,name:"terror",selected: true},{id: 2,name:"comics",selected: false},{id: 3,name:"suspense",selected: true}
我尝试使用下面的filter
,但不起作用,我该怎么办?
a2.filter(data => {
return a1.find(value => {
let x = data.id === value.id ? {
id: value.id,
text: value.name,
selected: true
} : {
id: data.id,
text: data.name,
selected: false
}
})
})
发布于 2018-06-05 08:26:15
您不应该使用filter
,因为您需要一个具有与开始时相同数量的项目的输出数组-使用map
创建一个新的数组,该数组的元素数量与原始数组相同,只是经过了转换。
由于a2
看起来没有任何新的信息,并且仅通过显示某些对象的存在或缺失而有用,因此一个复杂度较低的方法是对id
s的Set
执行map
a2
,然后通过迭代a1
并检查它们的id
s是否在Set
中来生成新对象
let a1 = [{id: 1, name: "terror"}, {id: 2, name: "comics"}, {id: 3, name: "suspense"}]
let a2 = [{id: 1, name: "terror"}, {id: 3, name: "suspense"}]
const a2IDs = new Set(a2.map(({ id }) => id));
const output = a1.map((item) => ({ ...item, selected: a2IDs.has(item.id) }));
console.log(output);
可以通过将.filter
更改为.map
并按原样使用.find
来修复代码以使其正常工作,但这会有更大的复杂性,因为它每次都必须迭代a2
中的项(相比之下,Set
查找就是O(1)
)。
https://stackoverflow.com/questions/50690425
复制相似问题