2017-08-09 53 views
0

看起來像一個簡單的任務,但我發現很難實現。 我有一個包含子對象的對象,並在它們上面循環時,我想根據其中一個字段的值(該字段存在於每個內部對象中)刪除一個內部對象。從Javascript中的父對象中刪除子對象

循環是這樣的:

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 if you possible ..thx

+0

ü可以請出示你的HTML ? –

+0

刪除是什麼意思?從數組中刪除/替換爲未定義/做一個DOM刪除? –

+0

「this.updated_items」究竟是什麼?一個數組,一個'Map'?沒有這些信息就不可能回答這個問題。你所展示的是它是可迭代的。 – Bergi

回答

1

可以使用filter功能一個數組,並使用Array.from你的對象轉換爲數組:

this.update_items = Array.from(this.updated_items).fiter(old_item => old_item.content_id !== item.content_id) 
+0

它不是一個數組,它是一個包含子對象的對象(我發佈了或多或少相同的答案,然後才意識到這一點) –

+0

噢好吧,也許然後使用['數組。從'](// mdn.io/array.from)將解決這個問題 –

+0

我不知道OP的情況,但它與節點元素的列表(例如調用'myOl.children') –

1

您可以迭代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]; 
    } 
} 

由於對象#項不被一些瀏覽器的支持,另一種選擇是使用陣列#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 
    ) 
+0

我不確定使用'刪除'關鍵字是OP的意思 –

+0

據我瞭解,他想從一個對象中刪除一個屬性,刪除是這樣做的方式。如果他不這樣認爲,他會選擇另一個答案:) –

+0

你也不需要使用Object.entries,只是'for ... of'應該做到這一點(如果瀏覽器支持它) –