简体   繁体   English

根据属性值从ImmutableJS List中删除对象

[英]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? 基于属性值从List中删除对象的最简单方法是什么?

I'm looking for an equivalent of the $pull in MongoDB. 我正在寻找相当于MongoDB的$ pull。

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'. 我想从数组中删除与属性的对象的组为“1”。 In MongoDB, I'd do it like this: 在MongoDB中,我会这样做:

Model.update({_id: getCorrectParentObj},{ $pull: {listIDeleteFrom: { a: '1' } } },(err, result)=>{});

How can I get the same result with ImmutableJS? 如何使用ImmutableJS获得相同的结果?

You could simply filter the immutable list: 您可以简单地filter不可变列表:

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: 但是,对非空List filter会产生不同的不可变列表,因此您可能需要首先检查{a: 1}的出现次数:

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: 你不需要Immutable任何特定的东西,只需使用JavaScript数组原型:

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: 或者您可以通过反向条件从.filter()获取值:

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. 如果test变量已经是一个Immutable对象,那么首先用.toArray()转换它,然后重新.toArray()转换。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM