javascript - 基于另一个数组并组合过滤数组

标签 javascript arrays ecmascript-6

给定两个数组:

const inputOne = [
 {id: "valueA", prop: 123},
 {id: "valueB", prop: 456}
]

const inputTwo = [
 {id: "valueA", other: 54},
 {id: "valueB", other: 98},
 {id: "valueC", other: 11}
]

我正在尝试根据 inputOneid 过滤 inputTwo,然后合并在两者中找到的属性。

期望的输出:

combinedAndFiltered = [
 {id: "valueA", other: 54, prop: 123},
 {id: "valueB", other: 98, prop: 456}
]

我尝试过mapfilter和/或reduce的各种组合,但不知何故无法理解它。

最佳答案

此解决方案假设只有两个集合,并且每个集合中的 id 属性是唯一的。

您可以通过以下方式基于公共(public)属性 (id) 创建两组合并对象的 an intersection:

  • 迭代第一个集合,然后在第二个集合中搜索第一个集合的当前元素。
  • 如果找到匹配项,则将两个对象组合成一个新对象,然后将该对象添加到累加器集中。
  • 返回累加器

此方法返回一个新集合,其中包含在两个集合中找到的合并对象。如果任一集合中缺少某个对象,则该对象将不会包含在输出中。

const inputOne = [ {id: "valueA", prop: 123}, {id: "valueB", prop: 456}, {id: "valueD", prop: 789} ]
const inputTwo = [ {id: "valueA", other: 54}, {id: "valueB", other: 98}, {id: "valueC", other: 11} ]

function intersectAndMerge(a, b) {
  const accumulator = []
  for(let { id, ...props } of a) {
    const match = b.find(e =>  e.id === id)
    if(match !== undefined) {
      accumulator.push({ ...match, ...props })
    }
  }
  return accumulator
}

console.log(intersectAndMerge(inputOne, inputTwo))

这也可以通过reduce循环来完成,但我发现它的可读性较差:

const inputOne = [ {id: "valueA", prop: 123}, {id: "valueB", prop: 456}, {id: "valueD", prop: 789} ]
const inputTwo = [ {id: "valueA", other: 54}, {id: "valueB", other: 98}, {id: "valueC", other: 11} ]

function intersectAndMerge(a, b) {
  return a.reduce((accumulator, { id, ...props }) => {
    const match = b.find(e =>  e.id === id)
    if(match !== undefined) {
      accumulator.push({ ...match, ...props })
    }
    return accumulator
  }, [])
}

console.log(intersectAndMerge(inputOne, inputTwo))

关于javascript - 基于另一个数组并组合过滤数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54014075/

相关文章:

javascript - 原型(prototype)继承和扩展现有对象

javascript - 如何在 webdriverjs 中执行自定义 javascript 代码

返回 php 代码数组 bool 值

javascript - 如何在不循环的情况下更新数组内的 JS 对象值?

javascript - 带有 babel-loader 的 Webpack 无法识别 import 关键字

javascript - 检查字段是否包含数据并且其中一个是数字

javascript - 等待一个事件完成然后执行另一个事件的问题

arrays - 在字节数组上使用json.Unmarshal()时出现问题

jquery - 从键中查找数组中的值

javascript - Browserify错误{错误: Plugin 1 specified in "base" provided an invalid property of "loose" while parsing file: mypath\react-app. js