How to delete items from an array inside objects.
It should remove all the hobbies that are dance.
I tried to use splice.
const people = [{
id: 1,
documents: [{
id: 1,
category: [{
hobby: 'soccer'
}, {
hobby: 'dance'
}]
},
{
id: 2,
category: [{
hobby: 'soccer'
}, {
hobby: 'dance'
}]
}
]
},
{
id: 2,
documents: [{
id: 1,
category: [{
hobby: 'dance'
}, {
hobby: 'soccer'
}]
},
{
id: 2,
category: [{
hobby: 'soccer'
}, {
hobby: 'dance'
}]
}
]
}
];
people.forEach(person => {
person.documents.forEach(document => {
document.category.forEach((cat, index) => {
if (cat.hobby === 'dance') {
document.category.splice(index, 1)
}
})
})
})
console.log(people);
>Solution :
Your code is almost correct, but there is a slight issue when using forEach to modify an array while iterating it. This can lead to skipping elements or incorrect results. Instead, use the filter method to create a new array with only the elements that don’t match the condition.
people.forEach(person => {
person.documents.forEach(document => {
document.category = document.category.filter(cat => cat.hobby !== 'dance');
})
});
console.log(people);
This iterates through each person, document, and category using forEach, but instead of directly modifying the category array, it reassigns the category array to a new array with only the elements where the hobby is not ‘dance’. This prevents any issues related to modifying the array while iterating it.