问题描述
我有一个不可变的OrderedMap,如下所示:
I have an Immutable OrderedMap as follows:
pairs: Immutable.OrderedMap({"Key1":"Value1","Key2":"Value2","Key4":"Value4"})
我需要在["Key2":"Value2"]之后动态插入["Key3":"Value3"].
I need to insert ["Key3":"Value3"] after ["Key2":"Value2"] dynamically.
我以为
pairs.MergeIn(['Key2'],OrderedMap({"Key3":"Value3"}))
将达到目的,但不起作用.
will serve the purpose but not working.
我尝试了
const newPairs=Immutable.OrderedMap();
newPairs.forEach(function(value,key,map)){
if(key=="Key4")
newPairs.set('Key3','Value3')
newPairs.set(key,value')
});
但是我知道这是一个愚蠢的代码,因为newPairs是不可变的,并且newPairs将仍然为空,因此它无法正常工作.那么,OrderedMap.addBefore(Key,key,value)有什么不可变的方法吗?
But I know it's a stupid code which won't work as newPairs is immutable and newPairs will be still empty.So is there any Immutable way of OrderedMap.addBefore(Key,key,value)?
推荐答案
OrderedMap
保留插入顺序,因此您只需要创建一个新的 OrderedMap
即可,插入正确的位置:
OrderedMap
preserves the order of insertions, so you just need to create a new OrderedMap
where the value is inserted at the correct place:
function printMap(map) {
map.entrySeq().map(([key, val]) => console.log(key, val)).toJS()
}
function insertBefore(map, index, key, val) {
return Immutable.OrderedMap().withMutations(r => {
for ([k, v] of map.entries()) {
if (index === k) {
r.set(key, val)
}
r.set(k, v)
}
});
}
const o1 = Immutable.OrderedMap().set('key1', 'val1').set('key2', 'val2');
printMap(o1)
console.log('now insert before');
printMap(insertBefore(o1, 'key2', 'key1.1', 'val1.1'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.1/immutable.min.js"></script>
这篇关于不可变的JS OrderedMap:在给定的Key之后插入一个新条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!