Sorting using nested field in ramda.js

不问归期 提交于 2020-12-12 08:50:31

问题


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

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