簡體   English   中英

如何使用javascript比較數組對象中的元素

[英]How to compare elements in array objects using javascript

我是 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 完成這項工作的建議。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM