繁体   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