问题描述
我是 JavaScript 的新手。 我需要比较来自两个不同数组对象的字段,这些对象具有如下列表。
Array - A
[
{
"id": "xyz","number": "123","place": "Here","phone": "9090909090"
},{
"id": "abc","number": "456","place": "There","phone": "9191919191"
},]
Array - B
[
{
"element1" : "ert","id1":"iii","element2":"erws","element3":"234"
},{
"element1" : "uio","id1":"xyz","element2":"puy","element3":"090"
}
]
场景是将数组 A 的列表中的每个 'id' 与数组 B 的列表中的字段 'id1' 进行比较
示例 -
我需要检查数组 A -> 'id:xyz' 匹配数组 B 对象字段 'id1'。 数组 A - id: xyz 应与数组 B 中的 id1: xyz 匹配 如果匹配发生,我需要从数组列表 A 中取出完整的对象。
此处 id:xyz 与 id1:xyz 匹配
然后如下拉出
[
{
"id": "xyz","phone": "9090909090"
}
]
请帮助我提出使用 javascript 完成这项工作的建议。
解决方法
const A = [
{
"id": "xyz","number": "123","place": "Here","phone": "9090909090"
},{
"id": "abc","number": "456","place": "There","phone": "9191919191"
},];
const B = [
{
"element1" : "ert","id1":"iii","element2":"erws","element3":"234"
},{
"element1" : "uio","id1":"xyz","element2":"puy","element3":"090"
}
];
const C = A.filter(a => B.some(b => b.id1 === a.id));
console.log(C);
// the usage of `const` here means that arrA cannot be re-declared
// this is good for data that should not be changed
const arrA = [{
"id": "xyz","phone": "9090909090"
},"phone": "9191919191"
},];
const arrB = [{
"element1": "ert","id1": "iii","element2": "erws","element3": "234"
},{
"element1": "uio","id1": "xyz","element2": "puy","element3": "090"
}
];
// slow method for long lists,fine for short lists or if there are duplicates
// compares each entry in array A to each entry in array B
const out1 = arrA.filter(x => arrB.some(y => x.id === y.id1));
console.log("Example 1: \n",out1);
// faster for long lists
// creates a set of unique values for array B's id1 parameter,ignores duplicates
// then checks that set for each entry in array A
const setB = arrB.reduce((a,b) => {
a.add(b.id1);
return a;
},new Set());
const out2 = arrA.filter(x => setB.has(x.id));
console.log("Example 2: \n",out2)
.as-console-wrapper { min-height: 100% } /* this is just to make the stack overflow output prettier */