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

ahy6op9u  于 2021-09-23  发布在  Java
关注(0)|答案(2)|浏览(319)

我不熟悉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实现此功能的建议。

sd2nnvve

sd2nnvve1#

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

s71maibg2#

// 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 */

相关问题