如何从对象内部的数组中删除项。
它应该删除所有的爱好是舞蹈。我尝试使用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);
完全没有必要,但我个人喜欢这种任务的集合:
function deleteHobbyFrom(people, hobby) {
people.forEach(person => {
person.documents.forEach(document => {
const catAsSet = new Set(document.category)
catAsSet.forEach(cat => {
cat.hobby &&
cat.hobby === hobby &&
catAsSet.delete(cat)
})
document.category = Array.from(catAsSet)
})
})
}
我不认为我通常会像这里一样从数组转换回数组,但可以考虑使用set作为你的数据结构,而不是数组。