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. 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. There are more simplified and better solutions in 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. You can check running JSfiddle link.
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. each of those objects has a key 'docs' that contains an array with two objects. Those objects each have two keys 'id' and '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.
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])
}
}