user3696212
user3696212

Reputation: 3439

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?

Upvotes: 19

Views: 18166

Answers (3)

okm
okm

Reputation: 23871

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' });
}

Upvotes: 23

yaya
yaya

Reputation: 1

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

Upvotes: -7

Blakes Seven
Blakes Seven

Reputation: 50406

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.

Upvotes: -7

Related Questions