簡體   English   中英

在另一個數組中查找對象數組的索引

[英]Find index of array of objects inside another array

I have 2 array of objects with as shown below.    
I want to find the index by searching the child array 'sub' in parent array 'array1' keeping id as the key.

我想在 array1 中搜索子數組並找到像 [0,1,2,3] 這樣的值的索引。

Hence my expected output should be [0,1,2,3].    
Please help me out on this.



//parent array    
 array1 = [
    { "id": "1111", "name": "a1"},
    { "id": "2222", "name": "a2" },
    { "id": "3333", "name": "a3" },
    { "id": "4444", "name": "a4" },
    {"id": "5555", "name": "a5" },
];


//child array
 sub = [
    { "id": "1111"},
    { "id": "2222" }        
];

我正在努力在父數組上找到子數組,因為它包含具有鍵值的對象數組。

您可以對sub的所有id使用Set ,然后過濾array1的所見id的索引。

 const array1 = [{ id: "1111", name: "a1" }, { id: "2222", name: "a2" }, { id: "3333", name: "a3" }, { id: "4444", name: "a4" }, { id: "5555", name: "a5" }], sub = [{ id: "1111" }, { id: "2222" }], subIds = new Set(sub.map(({ id }) => id)), result = [...array1.keys()].filter(i => subIds.has(array1[i].id)); console.log(result);

const array1 = [
  { id: "1111", name: "a1" },
  { id: "2222", name: "a2" },
  { id: "3333", name: "a3" },
  { id: "4444", name: "a4" },
  { id: "5555", name: "a5" },
];

//child array
const sub = [{ id: "1111" }, { id: "2222" }];

const indexes = [];

for (let i = 0; i <= sub.length - 1; i++) {
    const subID = sub[i].id;
  for (let j = 0; j <= array1.length - 1; j++) {
      const parentID = array1[j].id;

      if(parentID === subID){
          indexes.push(subID)
      }
  }
}

暫無
暫無

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

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