javascript - 如何过滤掉数组之间的匹配,并添加一个额外的键/值?
问题描述
我有 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'
}]
解决方案
您可以使用map
和some
这里的想法是
- 首先将两个数组合并到一个临时变量中。
- 获取变量中第一个数组的长度。
- 现在映射到合并的数组上,并且每个索引都小于
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)
推荐阅读
- c# - 当我创建/编辑自定义组合框时,键盘的 Blinker/Caret 被禁用
- node.js - 解决递归 socket.on("data") 调用
- java - 关于命令行程序输入的问题
- svelte-3 - 过滤 Svelte Promise 的结果
- python - 将 3D numpy 数组合并到 pandas Dataframe + 1D 向量中
- android - Firebase Kotlin Auth 在整个应用程序中保持登录
- php - 如何将现有模型作为多对多关系添加到 laravel 中的 dummy_mode
- javascript - 如何从 package.json 脚本运行 TypeScript 函数
- sql-server - FIELDQUOTE BULK INSERT 引号不会从加载的数据中删除
- swift - 如何在 UIScrollView 的子视图中使用 TouchEvent