Delete object from ImmutableJS List based upon property value

蹲街弑〆低调 提交于 2019-12-03 22:34:04
okm

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

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.

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