19

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?

Mark Amery
  • 143,130
  • 81
  • 406
  • 459
user3696212
  • 3,381
  • 5
  • 18
  • 31
  • Plain js: `listIDeleteFrom = listIDeleteFrom.filter(function(item) { return item.a !== 1 });` (not sure about immutable, hence the comment) – tymeJV Jul 17 '15 at 01:38

3 Answers3

23

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' });
}
Mark Amery
  • 143,130
  • 81
  • 406
  • 459
okm
  • 23,575
  • 5
  • 83
  • 90
  • 8
    Using [`filterNot`](https://facebook.github.io/immutable-js/docs/#/List/filterNot) instead of `filter` would arguably be slightly prettier. – Mark Amery Aug 18 '16 at 17:47
-7

You don't need Immutable any anything specific for this, just use JavaScript array prototypes:

var test = [{a: '1' , b: '1'},{a: '2' , b: '2'}];

test.map(function(el,idx) { 
    return ( el.a == "1") ? idx : -1 
} ).filter(function(el) { 
    return el != -1 
}).forEach(function(el) { 
   test.splice(el,1) 
});

Results in:

[ { "a" : "2", "b" : "2" } ]

Or you could just get the value from .filter() with a reverse condition:

test.filter(function(el) {
    return el.a != 1;
});

Which does not actually affect the array "in place", but you could always "overwrite" with the result.

If the test variable is already an Immutable object then just convert it with .toArray() first, and re-cast back.

Blakes Seven
  • 49,422
  • 14
  • 129
  • 135
-7

maybe you can try immutable-data

var immutableData = require("immutable-data")

var oldArray = [{a: '1' , b: '1'},{a: '2' , b: '2'}]

var data = immutableData(oldArray) 
var immutableArray = data.pick()

//modify immutableArray by ordinary javascript method
var i = 0
immutableArray.forEach(function(item,index){
  if (item.a === '1'){
    immutableArray.splice(index-i,1)
    i++
  }
})

var newArray = immutableArray.valueOf()

console.log(newArray)                    // [ { a: '2', b: '2' } ]
console.log(newArray[0]===oldArray[1])   // true
yaya
  • 1
  • 1