[英]Delete child object from parent object in Javascript
似乎是一項簡單的任務,但我發現很難達到。 我有包含子對象的對象,並且在遍歷它們時,我想根據其一個字段的值(每個內部對象中都存在該字段)刪除一個內部對象。
循環如下所示:
for (let old_item of this.updated_items) {
if (old_item['content_id'] === item.content_id) {
this.updated_items.***DELETE***(old_item)
}
}
我標記了缺少邏輯的位置。 我將如何刪除old_item
從this.updated_items
? 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
)
您可以對數組使用filter
函數,並使用Array.from
將對象轉換為數組:
this.update_items = Array.from(this.updated_items).fiter(old_item => old_item.content_id !== item.content_id)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.