似乎是一项简单的任务,但我发现很难实现。 我有包含子对象的对象,在循环它们时,我想根据其字段之一的值删除内部对象(该字段存在于每个内部对象中)。
循环是这样的:
for (let old_item of this.updated_items) {
if (old_item['content_id'] === item.content_id) {
this.updated_items.***DELETE***(old_item)
}
}
我标记了缺少逻辑的位置。
如何从 this.updated_items
中删除 old_item
?
ES6 如果可能的话..thx
最佳答案
您可以迭代 Object#entries ,当在值上找到正确的 content_id
时,从原始对象中删除该键。
for (const [key, value] of Object.entries(this.updated_items)) {
if (value.content_id === item.content_id) {
delete this.updated_items[key];
}
}
由于某些浏览器不支持 Object#entries,另一种选择是使用 Array#forEach 迭代对象的键,如果找到 content_id
,则从原始对象中删除该键:
Object.keys(this.updated_items) // get the object's keys
.forEach((key) => // iterate the keys
this.updated_items[key].content_id === item.content_id // if the content id is similar
&&
delete this.updated_items[key] //delete the key from the original object
)
关于javascript - Javascript中从父对象中删除子对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45595204/