2 回答
TA贡献1828条经验 获得超4个赞
使用 R.path 获取data.age:
const sortByYoungest = R.sortBy(R.path(['data', 'age']))
const people = [{"name":"Emma","data":{"age":70}},{"name":"Peter","data":{"age":78}},{"name":"Mikhail","data":{"age":62}}];
const result = sortByYoungest(people);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js" integrity="sha256-buL0byPvI/XRDFscnSc/e0q+sLA65O9y+rbF+0O/4FE=" crossorigin="anonymous"></script>
从尼克的答案sortByPath中获取一页,您可以使用 R.pipe创建一个可重用的函数:
const sortByPath = R.pipe(R.path, R.sortBy)
const sortByYoungest = sortByPath(['data', 'age'])
const people = [{"name":"Emma","data":{"age":70}},{"name":"Peter","data":{"age":78}},{"name":"Mikhail","data":{"age":62}}];
const result = sortByYoungest(people);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js" integrity="sha256-buL0byPvI/XRDFscnSc/e0q+sLA65O9y+rbF+0O/4FE=" crossorigin="anonymous"></script>
TA贡献1877条经验 获得超1个赞
当你想按路径排序时data.age,你可以从你的对象中获取道具data,使用R.prop它会给你一个对象,然后R.prop()在该对象上再次使用来获取age属性。要创建执行此操作的函数,您可以使用R.compose():
const byAge = R.ascend(R.compose(R.prop('age'), R.prop('data')));
const people = [
{ name: 'Emma', data:{ age: 70 }},
{ name: 'Peter', data:{ age: 78 }},
{ name: 'Mikhail', data:{ age: 62 }},
];
const peopleByYoungestFirst = R.sort(byAge, people);
console.log(peopleByYoungestFirst);
//=> [{"name":"Mikhail","data":{"age":62}},{"name":"Emma","data":{"age":70}},{"name":"Peter","data":{"age":78}}]
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js" integrity="sha256-buL0byPvI/XRDFscnSc/e0q+sLA65O9y+rbF+0O/4FE=" crossorigin="anonymous"></script>
要分解上述 compose 函数,假设您有 object obj,即:
obj = { name: 'Emma', data:{ age: 70 }}
表演R.prop('data')(obj)将给予:
{ age: 70 }
由于您对age返回对象的属性感兴趣,您可以再次R.prop('age')在上述对象上运行:
R.prop('age')({age: 70})
这会给70. 所以上面的行可以写成:
R.prop('age')(R.prop('data')(obj))
^^^^^ f ^^^^^ ^^^^^^ g ^^^^^ ^ x
然而,这个函数的问题是它没有返回一个我们可以传递obj进去的函数70。目前它采用 的形式f(g(x)),通过组合它,我们可以得到 的形式(f.g)(x),其中f.g组合函数f并g产生一个新函数。要在 Ramda 中作曲,我们可以使用R.compose():
R.compose(R.prop('age'), R.prop('data'))(obj)
这可以通过 eta-reduced 去除obj示例中的内容。
这种方法可以推广到:
const {pipe, split, reverse, map, apply, compose, ascend} = R;
const makeSortFn = compose(ascend, pipe(split('.'), reverse, map(R.prop), apply(compose)));
const byAge = makeSortFn('data.age');
const people = [
{ name: 'Emma', data:{ age: 70 }},
{ name: 'Peter', data:{ age: 78 }},
{ name: 'Mikhail', data:{ age: 62 }},
];
const peopleByYoungestFirst = R.sort(byAge, people);
console.log(peopleByYoungestFirst);
//=> [{"name":"Mikhail","data":{"age":62}},{"name":"Emma","data":{"age":70}},{"name":"Peter","data":{"age":78}}]
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js" integrity="sha256-buL0byPvI/XRDFscnSc/e0q+sLA65O9y+rbF+0O/4FE=" crossorigin="anonymous"></script>
但相反,我更喜欢Ori 的方法,通过拆分字符串可以更容易地概括:
R.sortBy(R.path(path_str.split('.')))
添加回答
举报