Delete object from ImmutableJS List based upon property value

人走茶凉 提交于 2019-12-12 08:21:24

问题


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?


回答1:


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



回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/31466400/delete-object-from-immutablejs-list-based-upon-property-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!