如何使用JavaScript比较数组对象中的元素

3

我刚开始使用 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",
    "number": "123",
    "place": "Here",
    "phone": "9090909090"     
  }
 ]

请帮我提供使用JavaScript使这段代码能够正常运行的建议。


如果你发布你所尝试的内容,有人可能能够帮助你修复/完成它。 - Scott Hunter
2个回答

0

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);


1
抱歉,但是OP要求从数组A中过滤出数组B的输出(请参见他们的最终示例)。您提供了数组B的输出。 - LaytonGB
1
@LaytonGB 哎呀...谢谢,我会修正我的回答! - kol

0

// 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",
    "number": "123",
    "place": "Here",
    "phone": "9090909090"
  },
  {
    "id": "abc",
    "number": "456",
    "place": "There",
    "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 */


看看第二种方法有多快会很有趣。 - kol
你介意帮我理解一下 'filter' 和 'some' 函数的作用吗?并且能否解释一下这行代码 const out1 = arrA.filter(x => arrB.some(y => x.id === y.id1)); - Virat

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接