简体   繁体   English

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

[英]Ramdajs: How to filter a list based on a object property?

 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>

I want to get the objects whose hair is 'blond'.我想得到头发是“金发”的对象。 I tried using compose but unluckily it doesn't work.我尝试使用 compose 但不幸的是它不起作用。 I am still new with ramda.我还是 ramda 的新手。

Your initial attempt is almost correct;您最初的尝试几乎是正确的; R.props('attributes') should have been R.prop('attributes') instead: R.props('attributes')应该是R.prop('attributes')代替:

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

However you may find it easier to use pathSatisfies if you need to assert against a nested property:但是,如果您需要对嵌套属性进行断言,您可能会发现使用pathSatisfies更容易:

Returns true if the specified object property at given path satisfies the given predicate;如果给定路径上的指定对象属性满足给定谓词,则返回 true; false otherwise.否则为假。

 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>

References参考

  1. props道具
  2. prop支柱
  3. pathSatisfies路径满足

it is year 2020, I guess use pathEQ is much simple现在是 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);

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

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