I have a nested array of objects named dishes which has unique IDs in it. I want to find the index of the array if the id is present in foodItems in dishes and then remove it from foodItems
const dishes = [{
cuisine: 'Chinese',
foodItems: [{
id: '1',
dishName: 'Chicken noodles',
price: '6.00 USD'
},
{
id: '2',
dishName: 'Fried rice',
price: '5.00 USD'
},
{
id: '3',
dishName: 'Dumplings',
price: '2.00 USD'
}
],
},
{
cuisine: 'Indian',
foodItems: [{
id: '4',
dishName: 'Tikka masala',
price: '10.00 USD'
},
{
id: '5',
dishName: 'Naan Bread',
price: '2.00 USD'
},
{
id: '6',
dishName: 'Dal Fry',
price: '4.00 USD'
}
],
}
];
Here, is what I tried (Which is not working and returning undefined in index):
let removeId = (id) => {
let index = dishes.forEach(dish => dish.foodItems.findIndex(item => item.id === id)); // returns undefined
if (index !== -1) {
dishes.forEach(dish=> dish.foodItems.splice(index, 1)); // remove obj from foodItems array
return true;
} else {
return false;
}
}