Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete object from ImmutableJS List based upon property value

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?

like image 838
user3696212 Avatar asked Jul 16 '15 23:07

user3696212


People also ask

How to remove particular property from an object?

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.

How do I remove an item from an immutably array?

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.

How to delete object field in js?

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, ...

How do you remove an element from an object?

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.


1 Answers

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' });
}
like image 195
okm Avatar answered Oct 23 '22 09:10

okm