简体   繁体   English

使用ramda.js中的嵌套字段进行排序

[英]Sorting using nested field in ramda.js

In the documentation of sortBy , it says we can use R.prop to sort an object by it's field. sortBy的文档中,它说我们可以使用R.prop对对象进行字段排序。 But if I have to sort by a nested field, it does not work. 但是,如果我必须按嵌套字段排序,则无法正常工作。 For example R.prop('id.number') does not work. 例如R.prop('id.number')不起作用。

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. 我猜有一种我无法弄清楚的使用R.prop的正确方法。

您可以使用R.path来访问嵌套属性,因此您的示例将成为R.sortBy(R.path(['id', 'number']))

Unless I'm mistaken, id.number itself is being checked as a property, when in fact there is only the property id . 除非我弄错了, id.number本身被检查为属性,而实际上只有属性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 . R.prop()仅检查一个向下嵌套的结构是否超出其能力范围,并且被要求在不起作用后查找属性number

The documentation states that sortBy accepts a function which takes an element under consideration. 该文档指出sortBy接受一个函数,该函数接受一个正在考虑的元素。 The following is tested on the ramda.js REPL and works: 以下内容在ramda.js REPL上进行了测试,并且可以正常工作:

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. tl; dr匿名函数获胜。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM