yariv bar
yariv bar

Reputation: 976

Delete child object from parent object in Javascript

seemed like a simple task but im finding it hard to achive. I have object containing child objects, and while looping over them i would like to delete an inner object in based on value of one of it's fields (this field exists in every inner object).

the loop goes like this:

for (let old_item of this.updated_items) {
    if (old_item['content_id'] === item.content_id) {
        this.updated_items.***DELETE***(old_item)
    }
}

I marked location where is the missing logic. How would i delete old_item from this.updated_items? ES6 if possible..thx

Upvotes: 1

Views: 5011

Answers (2)

Ori Drori
Ori Drori

Reputation: 193348

You can iterate the Object#entries, and when the correct content_id is found on the value, delete the key from the original object.

for (const [key, value] of Object.entries(this.updated_items)) {
    if (value.content_id === item.content_id) {
        delete this.updated_items[key];
    }
}

Since Object#entries is not supported by some browsers, another option is to use Array#forEach to iterate the object's keys, and if the content_id is found delete the key from the original object:

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
     )

Upvotes: 3

Ulysse BN
Ulysse BN

Reputation: 11423

You can use the filter function over an array, and convert your object to an array using Array.from:

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

Upvotes: 1

Related Questions