我有两个数组,我想使用Arr2键在Arr1中找到该项目,并将arr2的值映射到arr1(如果未找到的值应为0)。
const Arr1=['A','B','C']
const Arr2=[{key:'a',val:100},{key:'c',val:100}]
预期结果:
const Arr3=[{key:'a',val:100},{key:'b',val:0},{key:'c',val:100}]
答案 0 :(得分:6)
const Arr1=['A','B','C']
const Arr2=[{key:'a',val:100},{key:'c',val:100}]
const Arr3 = Arr1.map(c => {
const exists = Arr2.find(b => b.key === c.toLowerCase());
return exists || { key: c.toLowerCase(), val: 0 };
})
console.log(Arr3)
或使用 reduce
:
const Arr1=['A','B','C']
const Arr2=[{key:'a',val:100},{key:'c',val:100}]
const Arr3 = Arr1.reduce((r, a) => {
const exists = Arr2.find(b => b.key === a.toLowerCase());
const item = exists || { key: a.toLowerCase(), val: 0 }
return r.concat(item)
},[])
console.log(Arr3)
答案 1 :(得分:1)
在上一个问题中,您仍然可以返回一个值,然后在比较之前将键转换为小写。
const Arr1=['a','b','c']
var Arr2=[{key:'a',val:100},{key:'c',val:100}]
Arr2.map(val => {
if(Arr1.indexOf(val.key) >= 0 )
val.val = val
else
val = 0
})
答案 2 :(得分:-1)
const Arr1= [{key:'a',val:100},{key:'c',val:120}]
let obj = Arr1.find(o => o.key === 'a');
console.log(obj); // your object