简体   繁体   English

在另一个对象数组中的对象数组中搜索 object

[英]Search for an object inside an array of objects inside another array of objects

Sorry about a confusing title.对不起,一个令人困惑的标题。 This is possibly a double but I couldn't find a solution.这可能是双重的,但我找不到解决方案。

So I have an array that simplified would look like this:所以我有一个简化的数组如下所示:

0:[
{ 
  docs: [{id: 1, title: 'title one'}, {id: 2, title: 'title two'}]
},
{ 
  docs: [{id: 3, title: 'title one'}, {id: 4, title: 'title two'}]
},
{ 
  docs: [{id: 5, title: 'title one'}, {id: 6, title: 'title two'}]
},
]

So I have an id by which I need to find the object on the deepest level.所以我有一个 id,我需要通过它在最深层次上找到 object。 How could I do that?我怎么能那样做? Thank you谢谢

 const my_array = [ { docs: [{id: 1, title: 'title one'}, {id: 2, title: 'title two'}] }, { docs: [{id: 3, title: 'title one'}, {id: 4, title: 'title two'}] }, { docs: [{id: 5, title: 'title one'}, {id: 6, title: 'title two'}] }, ] const id = 3;

As you mentioned solution in JavaScript so the following code will fulfill your requirements.正如您在 JavaScript 中提到的解决方案,因此以下代码将满足您的要求。 There are more simplified and better solutions in Jquery. Jquery中有更简化更好的解决方案。

var result = [];
var id = 3;

for(i=0; i < lst.length; i++){
  for(j=0; j < lst[i].docs.length; j++){
    if(lst[i].docs[j].id == id)
    result.push(lst[i].docs[j]);
  }
}

Here lst is your list.这里 lst 是你的清单。 You can check running JSfiddle link.您可以检查正在运行的JSfiddle链接。

This should work `这应该工作`

let result;
for(let i=0;i<my_array.length;i++)
{
 for(let j=0;j<my_array.length;j++)
 {
  if(my_array[i].docs[j].id==id)
  {
   result=my_array[i].docs[j];
   break;
  }
  if(!!result) break;
 }
}

` `

my_array is an array that contains 3 objects. my_array 是一个包含 3 个对象的数组。 each of those objects has a key 'docs' that contains an array with two objects.这些对象中的每一个都有一个键“docs”,其中包含一个包含两个对象的数组。 Those objects each have two keys 'id' and 'title'.这些对象每个都有两个键“id”和“title”。 You just have to loop through to find the one you want.你只需要循环查找你想要的那个。 Learning how to traverse arrays and objects can be confusing at first but it's an essential programming skill.学习如何遍历 arrays 和对象一开始可能会让人感到困惑,但这是一项基本的编程技能。

array elements are referenced with square bracket notation and objects are references through dot notation or square bracket with the keys in quotes.数组元素用方括号表示法引用,对象通过点表示法或方括号用引号括起来的键引用。 see example of both in the snippet请参阅代码段中的示例

 const my_array = [ { docs: [{id: 1, title: 'title one'}, {id: 2, title: 'title two'}] }, { docs: [{id: 3, title: 'title one'}, {id: 4, title: 'title two'}] }, { docs: [{id: 5, title: 'title one'}, {id: 6, title: 'title two'}] }, ] const id = 3; for(let i = 0; i < my_array.length; i++){ for(let j = 0; j < my_array[i].docs.length; j++){ if(my_array[i].docs[j].id == 3)console.log(my_array[i].docs[j]) if(my_array[i]['docs'][j]['id'] == 3)console.log(my_array[i]['docs'][j]) } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM