Reputation: 6746
I currently have an array of objects with each containing an array of objects.
My goal is to find a nested object
in a single line of javascript code. I am trying to avoid a nested loop, I know how to solve it that way but javascript offers a lot of elegant solutions for such scenarios.
This is how my data looks like:
const items = [
{
id: 1,
title: 'Test 1',
data: [
{
id: 3,
title: 'Test 3',
},
{
id: 4,
title: 'Test 4',
},
],
},
{
id: 2,
title: 'Test 2',
data: [
{
id: 5,
title: 'Test 5',
},
],
},
];
With a nested loop:
let item = null;
for (let i = 0; i<items.length; i++) {
for (let j = 0; j<items[i].data; j++) {
if (items[i].data[j].id == myId) {
item = items[i].data[j];
return;
}
}
}
I feel like there is a more simplistic and prettier solution than this.
Upvotes: 1
Views: 185
Reputation: 14198
In terms of performance, I would suggest the way is to use Array#reduce
combined with Array#find
const items = [{id:1,title:"Test 1",data:[{id:3,title:"Test 3",},{id:4,title:"Test 4",},],},{id:2,title:"Test 2",data:[{id:5,title:"Test 5",},],},];
const myId = 4;
const res = items.reduce((acc, {data}) => {
const foundItem = data.find(({id}) => id === myId);
if(foundItem)
acc.push(foundItem);
return acc;
}, [])
console.log(res);
Upvotes: 1
Reputation: 14871
You could do that in one line. As I saw in your nested loop solution, you find in each object's data, so first you could flatten the data in to array of objects and then find through that array
const items = [
{
id: 1,
title: "Test 1",
data: [
{
id: 3,
title: "Test 3",
},
{
id: 4,
title: "Test 4",
},
],
},
{
id: 2,
title: "Test 2",
data: [
{
id: 5,
title: "Test 5",
},
],
},
];
const myId = 4;
const res = items.flatMap((item) => item.data).find(({ id }) => id === myId);
console.log(res);
Upvotes: 2