let arr = [
{
id: 100,
name: 'bmw'
},
{
id: 101,
name" 'porsche'
}
];
let selected = [{id: 100}];
What is the Ramda way of getting a filtered list F based on the inputs (list, selected)?
let arr = [
{
id: 100,
name: 'bmw'
},
{
id: 101,
name" 'porsche'
}
];
let selected = [{id: 100}];
What is the Ramda way of getting a filtered list F based on the inputs (list, selected)?
Ramda has a function built-in which directly handles finding the single value. If you want to find all the ones in a list, you'll need to extend it a bit. But whereEq
tests an object to see if all the properties match those in a sample object. So you can do something like this:
const {find, whereEq, map} = R;
const arr = [
{id: 100, name: 'bmw'},
{id: 101, name: 'porsche'},
{id: 102, name: 'ferrari'},
{id: 103, name: 'clunker'}
]
console.log(find(whereEq({id: 101}), arr))
const choose = (all, selected) => map(sel => find(whereEq(sel), all), selected)
console.log(choose(arr, [{id: 101}, {id: 103}]))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>
Depending upon how you plan to use it, you might want to wrap choose
in curry
.
My take would be to break it down into a few parts.
// a function to grab the the id out of selected (index of 0, key of 'id')
const selectedId = path([0, 'id'])
const selectedValue = (selected, options) =>
filter(propEq('id', selectedId(selected)), options)
selectedValue(selected, arr) // [{"id": 100, "name": "bmw"}]
That’s a little difficult to read for my liking, so I’d then regroup some of the functions, and also use head
to get the result out of the array
const hasIdOf = pipe(selectedId, propEq('id'))
const selectedValueB = (selected, options) => pipe(
filter(hasIdOf(selected))),
head
)(options)
selectedValueB(selected, arr) // {"id": 100, "name": "bmw"}
propEq(‘id’)
returns a function that takes two more parameters. A value to test an id
property against, and an object with an id
property
pipe
composes many functions together, in this case, it’s passing options
to filter(...)
, and the result of that to head
head
returns item at index 0
You can break up the functions in many ways. Whatever you find most readable/reusable