Ramdajs:如何根据对象属性过滤列表?

时间:2018-12-10 09:40:11

标签: javascript ramda.js

const abby = {name: 'Abby', attributes: {age: 7, hair: 'blond'}};
const fred = {name: 'Fred', attributes: {age: 12, hair: 'brown'}};
const rusty = {name: 'Rusty', attributes: {age: 10, hair: 'brown'}};
const alois = {name: 'Alois', attributes: {age: 15, disposition: 'surly'}};
const kids = [abby, fred, rusty, alois];

console.log = function(text) {
$('#console').append($('<div>').text(text));
};

// current code
console.log(R.filter(R.compose(R.propEq('hair', 'blond'), R.props('attributes')))(kids));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script>

<div id="console"></div>

我想得到头发是“白”的物体。我尝试使用compose,但不幸的是它不起作用。我对ramda还是陌生的。

2 个答案:

答案 0 :(得分:3)

您的最初尝试几乎是正确的; R.props('attributes')应该改为R.prop('attributes')

R.filter(R.compose(R.propEq('hair', 'blond'), R.prop('attributes')))(kids)

但是,如果您需要对嵌套属性进行断言,可能会更容易使用pathSatisfies

  

如果给定路径上的指定对象属性满足给定谓词,则返回true;否则,返回true。否则为假。

const {filter, pathSatisfies, equals} = R;

const abby = {name: 'Abby', attributes: {age: 7, hair: 'blond'}};
const fred = {name: 'Fred', attributes: {age: 12, hair: 'brown'}};
const rusty = {name: 'Rusty', attributes: {age: 10, hair: 'brown'}};
const alois = {name: 'Alois', attributes: {age: 15, disposition: 'surly'}};
const kids = [abby, fred, rusty, alois];

console.log(

  filter(pathSatisfies(equals('blond'), ['attributes', 'hair']), kids)

)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script>

参考

  1. props
  2. prop
  3. pathSatisfies

答案 1 :(得分:0)

现在是2020年,我想使用pathEQ非常简单

const R = require("ramda");
let out = "";
const abby = { name: "Abby", attributes: { age: 7, hair: "blond" } };
const fred = { name: "Fred", attributes: { age: 12, hair: "brown" } };
const rusty = { name: "Rusty", attributes: { age: 10, hair: "brown" } };
const alois = { name: "Alois", attributes: { age: 15, disposition: "surly" } };
const kids = [abby, fred, rusty, alois];
out = R.filter(R.pathEq(["attributes", "hair"], "blond"))(kids);