问题
In the documentation of sortBy, it says we can use R.prop to sort an object by it's field. But if I have to sort by a nested field, it does not work. For example R.prop('id.number') does not work.
var items = [{id:3},{id:1},{id:2}];
var sorter = R.sortBy(R.prop('id'));
sorter(items)
works fine. But if I have a nested structure
var items = [{id:{number:3}},{id:{number:1}},{id:{number:2}}];
var sorter = R.sortBy(R.prop('id.number'));
sorter(items)
returns me an empty list. I guess there is a correct way of using R.prop that I am not able to figure out.
回答1:
You can use R.path
for accessing nested properties, so your example would become R.sortBy(R.path(['id', 'number']))
回答2:
Unless I'm mistaken, id.number
itself is being checked as a property, when in fact there is only the property id
. R.prop()
only checks one level down - nested structures are beyond its ability, and being asked to look for the property number
after doesn't work .
The documentation states that sortBy
accepts a function which takes an element under consideration. The following is tested on the ramda.js REPL and works:
var items = [{id:{number:3}},{id:{number:1}},{id:{number:2}}];
var sorter = R.sortBy(function(item) {return item['id']['number'];});
sorter(items)
It works by simply looking up the properties in succession.
tl;dr Anonymous functions for the win.
来源:https://stackoverflow.com/questions/36257219/sorting-using-nested-field-in-ramda-js