i have data like below,
const items = [
{
id: \'1\',
color: \'green\',
name: \'item1\',
polygons: [
{
You can run nested loops, or you can access the subitems directly and use some or filter but if you wanted full recursion here's a fairly verbose gist for the sake of explaining
const iterate = (obj) => {
// loop through object properties
Object.entries(obj).forEach(([key, value]) => {
if (obj.hasOwnProperty(key)) {
// do something with the current iteration
if (typeof value === 'object') {
// if the property value is an object then iterate into that object
iterate(value)
}
}
});
};
iterate(items);
a.findIndex(b => b.subItem.id ===2)
try the above solution. here a is the list you're using
but I have a solution/example
you have some structure like const a = [{id:'some1', subItem:{ id:1}},{id:'some2', subItem:{ id:2}}]
Below will return index for subItem with ID === 2
a.findIndex(b => b.subItem.id === 2);
const a = [{id:'some1', subItem:{ id:1}},{id:'some2', subItem:{ id:2}}]
//Below will return index for subItem with ID === 2
a.findIndex(b => b.subItem.id === 2);
to get both indexes
const matchedItemIndex = a.findIndex(b => b.subItem.id === 2);// return matched itemIndex
const matchedItem = a.find(b => b.subItem.id === 2);
const matchedSubItemIndex = a[matchedItemIndex].findIndex(b => b.id === matchedItem.id);// return mamtching subItemIndex
The correct search can be done like this:
items.findIndex((item) => item.subItems.some((sub) => sub.id == '2'))
Example:
const items = [{
id: '1',
color: 'green',
name: 'item1',
polygons: [{
id: '1',
coordinates: [{
latitude: '25.00',
longitude: '-25.99',
},
{
latitude: '15.00',
longitude: '-25.99',
},
{
latitude: '25.00',
longitude: '-35.99',
}
],
}],
subItems: [{
id: '1',
name: 'subitem-1',
color: 'green',
polygons: [{
id: '2',
coordinates: [{
latitude: '25.00',
longitude: '-25.99',
},
{
latitude: '15.00',
longitude: '-25.99',
},
{
latitude: '25.00',
longitude: '-35.99',
}
],
}]
}],
},
{
id: '2',
color: 'red',
name: 'item2',
polygons: [{
id: '3',
coordinates: [{
latitude: '25.00',
longitude: '-25.99',
},
{
latitude: '15.00',
longitude: '-25.99',
},
{
latitude: '25.00',
longitude: '-35.99',
}
],
}],
subItems: [{
id: '2',
name: 'subitem-1',
color: 'red',
polygons: [{
id: '5',
coordinates: [{
latitude: '25.00',
longitude: '-25.99',
},
{
latitude: '15.00',
longitude: '-25.99',
},
{
latitude: '25.00',
longitude: '-35.99',
}
],
}]
}],
}
]
const itemIndex = items.findIndex((item) => item.subItems.some((sub) => sub.id == '2'));
console.log('Item index with subItems with id=2 is:', itemIndex)