首页 > 解决方案 > 如何过滤掉数组之间的匹配,并添加一个额外的键/值?

问题描述

我有 2 个包含对象的数组。每个对象都有一个“颜色”和“数字”的键/值对。我想检查这两个数组以找到与“数字”匹配的对象。找到这个之后,我想为原始数组中的所有对象添加一个键值对。

我有下面的例子,我相信它在正确的轨道上,但我正在努力找出如何继续。

基本上,如果对象匹配,我想将“匹配”的 K/V 对更改为真或假。

const array1 = [ {color: 'red', number: 1, match: ''}, {color: 'red', number: 2, match: ''}, {color: 'red', number: 3, match: ''} ]
const array2 = [ {color: 'red', number: 3, match: ''}, {color: 'blue', number: 5, match: ''}, {color: 'blue', number: 6, match: ''} ]

async function findMatchingObjects(array1, array2){
    const matchCheck = array1.filter(matchedObj => array2.includes(matchedObj));
  console.log(matchCheck);
}

findMatchingObjects(array1, array2);

预期输出将是:

const array3 = [{
  color: 'red',
  number: 1,
  match: 'false'
}, {
  color: 'red',
  number: 2,
  match: 'false'
}, {
  color: 'red',
  number: 3,
  match: 'true'
},
{
  color: 'red',
  number: 3,
  match: 'true'
}, {
  color: 'blue',
  number: 5,
  match: 'false'
}, {
  color: 'blue',
  number: 6,
  match: 'false'
}]

标签: javascriptarrays

解决方案


您可以使用mapsome

这里的想法是

  • 首先将两个数组合并到一个临时变量中。
  • 获取变量中第一个数组的长度。
  • 现在映射到合并的数组上,并且每个索引都小于length1匹配它,array2否则匹配它array1

const array1 = [ {color: 'red', number: 1, match: ''}, {color: 'red', number: 2, match: ''}, {color: 'red', number: 3, match: ''} ]
const array2 = [ {color: 'red', number: 3, match: ''}, {color: 'blue', number: 5, match: ''}, {color: 'blue', number: 6, match: ''} ]

let temp = [...array1,...array2]
let length1 = array1.length
let op = temp.map((inp,index)=> ({...inp, match: (index < length1 ?array2 : array1).some(({number})=> number === inp.number)}))

console.log(op)


推荐阅读