javascript ImmutableJS - 从 Map 中删除元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31128425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ImmutableJS - delete element from Map
提问by user3696212
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). How can I do it? I tried this, but something is wrong:
我想从中删除 2: {} (当然 - 没有这个就返回新集合)。我该怎么做?我试过这个,但出了点问题:
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
回答by Johann Echavarria
Just use the deletemethod and the property in double quotes:
只需使用delete方法和双引号中的属性:
theFormerMap = theFormerMap.delete("2")
回答by gabrielf
Just use the deletemethod 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
以下方法创建:
Immutable.fromJS({1: {}, 2: {}}).delete(2)
=> Map { "1": Map {}, "2": Map {} }
Key 2 is not removed as it is, in fact, a string key. The reason is that javascript objects convert numeric keys to strings.
键 2 没有被删除,因为它实际上是一个字符串键。原因是 javascript 对象将数字键转换为字符串。
However Immutable.js does support maps with integer keys if you construct them without using fromJS
:
但是 Immutable.js 确实支持带有整数键的映射,如果你在不使用的情况下构造它们fromJS
:
Immutable.Map().set(1, Immutable.Map()).set(2, Immutable.Map()).delete(2)
=> Map { 1: Map {} }
回答by yaya
If you use immutable-data:
如果您使用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