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;
}
}
CodePudding user response:
You need to include the rest of your logic in the forEach()
callback method. However, taking into account that you want to return true
once the item has been removed, it's easier to use a for ... of
loop:
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'
}
],
}
];
const removeId = (id) => {
for (let dish of dishes) {
const index = dish.foodItems.findIndex(fi => fi.id === id);
if (index > -1) {
dish.foodItems.splice(index, 1);
return true;
}
};
return false;
}
console.log(removeId('1'));
console.log(removeId('4'));
console.log(removeId('7'));
console.log(dishes);
CodePudding user response:
You can try this, using a for of and add entries variable what you for loop
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",
},
],
},
];
for (const [idx, items] of dishes.entries()) {
console.log(items.foodItems)
}
for the documentation in here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of