Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ramda: How can I filter data with nested objects?

const articles = [
    {title: 'title 1', published: false, pages: 30, tags: {name: 'work', id: 1, visibility: "everyone"}},
    {title: 'title 2', published: false, pages: 25, tags: {name: 'home', id: 3, visibility: "myself"}},
    {title: 'title 3', published: true, pages: 30, tags: {name: 'vacation', id: 5, visibility: "myself"}}
];

My JSON data looks something like this and I need to filter based on the value where published is true and visibility is myself. How can I achieve this in efficient manner? Would appreciate any help with this.

So far I have only been able to filter using single attribute

  R.filter(R.propEq("published", false))(articles);
like image 537
muskrat_ Avatar asked Sep 01 '25 01:09

muskrat_


2 Answers

Something like this:

R.filter(
  R.allPass([
    R.propEq("published", false),
    R.pathEq(["tags", "visibility"], "myself")
  ])
)(articles);
like image 79
mzedeler Avatar answered Sep 02 '25 15:09

mzedeler


You could use a spec object:

const predicate = R.where({
  published: R.equals(true),
  tags: R.where({
    visibility: R.equals('myself'),
  }),
});


// ==

const data = [
  {title: 'title 1', published: false, pages: 30, tags: {name: 'work', id: 1, visibility: "everyone"}},
  {title: 'title 2', published: false, pages: 25, tags: {name: 'home', id: 3, visibility: "myself"}},
  {title: 'title 3', published: true, pages: 30, tags: {name: 'vacation', id: 5, visibility: "myself"}}
];

console.log(
  R.filter(predicate, data),
);
<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>
like image 43
Hitmands Avatar answered Sep 02 '25 15:09

Hitmands