What would be the simplest way to delete an object from a List based on a value of a property?
I'm looking for an equivalent of the $pull in MongoDB.
My List looks simple like this:
[{a: '1' , b: '1'},{a: '2' , b: '2'}]
And I'd like to remove from the array the object with property a set to '1'. In MongoDB, I'd do it like this:
Model.update({_id: getCorrectParentObj},{ $pull: {listIDeleteFrom: { a: '1' } } },(err, result)=>{});
How can I get the same result with ImmutableJS?
Remove Property from an ObjectThe delete operator deletes both the value of the property and the property itself. After deletion, the property cannot be used before it is added back again. The delete operator is designed to be used on object properties. It has no effect on variables or functions.
Get the array and the index. Form an ArrayList with the array elements. Remove the specified index element using remove() method. Form a new array of the ArrayList using mapToInt() and toArray() methods.
In JavaScript, there are 2 common ways to remove properties from an object. The first mutable approach is to use the delete object. property operator. The second approach, which is immutable since it doesn't modify the original object, is to invoke the object destructuring and spread syntax: const {property, ...
Answer: Use the delete Operator You can use the delete operator to completely remove the properties from the JavaScript object. Deleting is the only way to actually remove a property from an object.
You could simply filter
the immutable list:
var test = Immutable.List.of(Immutable.Map({a: '1'}), Immutable.Map({a: '2'}));
test = test.filter(function(item) { return item.get('a') !== '1' });
However, filter
on non-empty List
would result a different immutable list, thus you may want to check the occurrence of {a: 1}
first:
if (test.some(function(item) { return item.get('a') === '1'; })) {
test = test.filter(function(item) { return item.get('a') !== '1' });
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With