Red*_*ant 3 javascript sorting immutable.js
请检查这个小提琴示例
如何orderedMap通过键sequence按降序对对象进行排序?我知道有一种sortBy方法,但文件没有给出一个更清晰的例子.
这是我的原始对象:
var props = {
"item": {
"A": {
"sequence": 5
},
"B": {
"sequence": null
},
"C":{
"sequence": 2
}
}
}
Run Code Online (Sandbox Code Playgroud)
我希望结果如下:
var props = {
"item": {
"A": {
"sequence": 5
},
"C":{
"sequence": 2
},
"B": {
"sequence": null
}
}
}
Run Code Online (Sandbox Code Playgroud)
示例代码:
var data = Immutable.fromJS(props,(key, value)=>{
var isIndexed = Immutable.Iterable.isIndexed(value);
return isIndexed ? value.toList() :value.toOrderedMap();
});
var sorted = data.get('item').sortBy((item) => item.get('sequence'));
console.log(sorted.toJS())
Run Code Online (Sandbox Code Playgroud)
Van*_*nic 10
您提供的功能sortBy()是比较器,它需要返回一个数字.通过在结果前面item.get('sequence')或后面添加一个减号,reverse()您将反转排序,获得您想要的输出.
这是一个例子:
var sorted = data.get('item').sortBy((item) => -item.get('sequence'));
// or var sorted = data.get('item').sortBy((item) => item.get('sequence')).reverse();
// you can now use .map() to go through your OrderedMap which has been
// sortbed by the sequence property and would look like your desired output
Run Code Online (Sandbox Code Playgroud)
请注意,您正在使用OrderedMap,并且只是调用sorted.toJS()将返回一个常规JS对象,其中键显然没有排序.
// If you need to iterate through the map and return some
// plain JS you can do something like:
sorted.map(x => x.get('sequence')).toJS()
// => Object {A: 5, C: 2, B: null}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7393 次 |
| 最近记录: |