简体   繁体   English

ImmutableJS - 从Map中删除元素

[英]ImmutableJS - delete element from Map

I have a map with this structure: 我有一个这种结构的地图:

{
1: {},
2: {}
}

And I'd like to delete 2: {} from it (of course - return new collection without this). 我想从它中删除2:{}(当然 - 如果没有这个,则返回新的集合)。 How can I do it? 我该怎么做? I tried this, but something is wrong: 我试过这个,但有些不对劲:

 theFormerMap.deleteIn([],2) //[] should mean that it's right in the root of the map, and 2 is the name of the object I want to get rid of

只需在双引号中使用delete方法和属性:

theFormerMap = theFormerMap.delete("2")

Just use the delete method and pass the property you want to delete: 只需使用delete方法并传递要删除的属性:

theFormerMap = theFormerMap.delete(2)

If this does not work then you have probably created theFormerMap using fromJS : 如果这不起作用,那么你可能theFormerMap使用fromJS创建了fromJS

Immutable.fromJS({1: {}, 2: {}}).delete(2)
=> Map { "1": Map {}, "2": Map {} }

Key 2 is not removed as it is, in fact, a string key. 键2不会被删除,实际上是一个字符串键。 The reason is that javascript objects convert numeric keys to strings. 原因是javascript对象将数字键转换为字符串。

However Immutable.js does support maps with integer keys if you construct them without using fromJS : 但是,如果在不使用fromJS情况下构造它们,Immutable.js确实支持具有整数键的映射:

Immutable.Map().set(1, Immutable.Map()).set(2, Immutable.Map()).delete(2)
=> Map { 1: Map {} }

If you use immutable-data : 如果您使用不可变数据

var immutableData = require("immutable-data")
var oldObj = {
  1: {},
  2: {}
}
var data = immutableData(oldObj) 
var immutableObj = data.pick()

//modify immutableObj by ordinary javascript method
delete immutableObj[2]

var newObj = immutableObj.valueOf()

console.log(newObj)                  // { '1': {} }
console.log(newObj===oldObj)         // [ { a: '2', b: '2' } ]
console.log(newObj[1]===oldObj[1])   // true

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

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