首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >合并两个map对象并返回自定义对象javascript

合并两个map对象并返回自定义对象javascript
EN

Stack Overflow用户
提问于 2018-06-05 08:21:58
回答 1查看 208关注 0票数 3

我有两个数组

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
    }
  })
})
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-05 08:26:15

您不应该使用filter,因为您需要一个具有与开始时相同数量的项目的输出数组-使用map创建一个新的数组,该数组的元素数量与原始数组相同,只是经过了转换。

由于a2看起来没有任何新的信息,并且仅通过显示某些对象的存在或缺失而有用,因此一个复杂度较低的方法是对ids的Set执行map a2,然后通过迭代a1并检查它们的ids是否在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))。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50690425

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档