Add an Item in OrderedMap with Immutable.js

好久不见. 提交于 2019-12-10 22:15:27

问题


How can I add an Item at the end of an OrderedMap ?

I tried

    this.boxes = this.boxes.setIn(data);

Thanks for any help


回答1:


One possible way of doing it is using concat

var boxes = Immutable.OrderedMap({
  box1: {
    id:1
  },
  box2: {
    id:2
  }
});

var data = Immutable.fromJS({
  box3: {
    id:3
  }
});


var newBoxes = boxes.concat(data);
console.log(newBoxes.toJS());  

Will print out:

Object { box1: Object { id: 1 }, box2: Object { id: 2 }, box3: Object { id: 3 } }




回答2:


An OrderedMap doesn't really have an "end" per se. Also if you want to add an item to a Map you're going to need a key for it as well. So either you use the set method for adding a key-value pair:

this.boxes = this.boxes.set(key,data);

Or you convert it to a List, where you can add it to the end and also maintain a clear iteration order, meaning you do get to have an "end".

this.boxes = this.boxes.toList().push(data);


来源:https://stackoverflow.com/questions/35946015/add-an-item-in-orderedmap-with-immutable-js

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