我有 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'
}]
最佳答案
您可以使用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)
关于javascript - 如何过滤掉数组之间的匹配项,并添加额外的键/值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55304281/