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
2 Answers 2
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
)
5 Comments
delete keyword is what OP meantObject.entries but just a for...of should do the trick (if browser support it)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)
3 Comments
Array.from would solve this issuemyOl.children)
this.updated_items? An array, aMap? Without that information it's impossible to answer the question. All you've shown is that it is iterable.typeof()'s ofthis.updated_itemsand its content...which are the items, equal toObject