如何在不可变地图中对项目进行排序(交换)?
我想交换项目在Map
内的不可变列表内,
例如:
I want to swap items inside an immutable list within a Map
,
example:
const Map = Immutable.fromJS({
name:'lolo',
ids:[3,4,5]
});
我正在尝试使用拼接来进行交换,也尝试过使用insert()
不可变方法.
i am trying to use splice to do the swapping, also tried with insert()
an Immutable method.
让我说我想从[3, 4, 5]
交换到[3, 5, 4]
,我正在进行类似以下的事情:
Lets say i want to swap from [3, 4, 5]
to [3, 5, 4]
, i am truing something like this:
list.set('ids', list.get('ids').splice(2, 0, list.get('ids').splice(1, 1)[0])
使用 Immutable.js 对不可变数据结构中的元素进行排序的最佳方法是什么?
What's the best way to sort elements inside an Immutable data structures with Immutable.js ?
您应使用 List.withMutations()
为此:
You should use Map.update()
and List.withMutations()
for that matter:
map.update('ids', idsList => idsList.withMutations(function (idsList) {
let temp = idsList.get(2);
return idsList.set(2, idsList.get(1)).set(1, temp);
}));
请注意,我将您的list
重命名为map
-实际上是Map
.
对于简单的排序,请选择
Notice that I renamed your list
to map
- this is actually a Map
.
And for simple sorting go for
map.update('ids', idsList => idsList.sort(function (a, b) {
// magic
});