Immutable JS OrderedMap: Insert a new entry after a given Key

99封情书 提交于 2021-02-08 07:51:14

问题


I have an Immutable OrderedMap as follows:

pairs: Immutable.OrderedMap({"Key1":"Value1","Key2":"Value2","Key4":"Value4"})

I need to insert ["Key3":"Value3"] after ["Key2":"Value2"] dynamically.

I thought

pairs.MergeIn(['Key2'],OrderedMap({"Key3":"Value3"}))  

will serve the purpose but not working.

I tried

const newPairs=Immutable.OrderedMap();
newPairs.forEach(function(value,key,map)){
   if(key=="Key4")
     newPairs.set('Key3','Value3')
   newPairs.set(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)?


回答1:


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>


来源:https://stackoverflow.com/questions/43512897/immutable-js-orderedmap-insert-a-new-entry-after-a-given-key

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