javascript - 如何过滤掉数组之间的匹配项,并添加额外的键/值?

标签 javascript arrays

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

我有以下示例,我认为该示例处于正确的轨道上,但正在努力找出如何继续。

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

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'
}]

最佳答案

您可以使用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)

关于javascript - 如何过滤掉数组之间的匹配项,并添加额外的键/值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55304281/

相关文章:

javascript - 使 Protractor 等待 select 元素填充有在另一个 Select 元素中选择选项的选项

javascript - 如何在 jQuery 中使用事件捕获概念 this._on();

javascript - 从 jscript 执行 php url

Java检查数组是否已满,并将不同数组的一部分复制到另一个数组

javascript - 无法使 Gtranslate 语言在下拉列表中工作

javascript - 有些表情符号与我的仅表情符号正则表达式不匹配

java - 复制公式 POI 的单元格值

python - 向量化 numpy 赋值

arrays - 如何在调用 Array#compact 时删除自定义类

javascript - 如何在javascript中更新子数组元素