Having the following array:
const vegsAndFruits = [
{
"fruit_banana": 10,
"fruit_apple": 1,
"veg_tomato": 3,
"fruit_watermelon": 11
},
{
"veg_carrot": 3,
"veg_garlic": 11,
"veg_potato": 0,
"fruit_apricot": 22
},
{
"veg_eggplant": 2,
"veg_cabbage": 1,
"fruit_strawberry": 100,
"fruit_orange": 30
}
]
I want to filter it to return the same array but to keep only the properties that start with "fruit".
Expected output
const expectedOutput = [
{
"fruit_banana": 10,
"fruit_apple": 1,
"fruit_watermelon": 11
},
{
"fruit_apricot": 22
},
{
"fruit_strawberry": 100,
"fruit_orange": 30
}
]
My attempt
I thought the solution should come from mixing ramda's R.startsWith() and R.pickBy(). But the following doesn't work as I expected:
const R = require("ramda")
R.map(R.pickBy(R.startsWith(["fruit"])),vegsAndFruits)
which returns
// [ {}, {}, {} ]
What am I missing here?
The R.pickBy predicate is called with the value (1st) and key (2nd) parameters. Since you need the key, use R.nthArg to create a function that returns the 2nd param:
const { map, pickBy, pipe, nthArg, startsWith } = R
const fn = map(pickBy(pipe(
nthArg(1),
startsWith('fruit')
)))
const vegsAndFruits = [{"fruit_banana":10,"fruit_apple":1,"veg_tomato":3,"fruit_watermelon":11},{"veg_carrot":3,"veg_garlic":11,"veg_potato":0,"fruit_apricot":22},{"veg_eggplant":2,"veg_cabbage":1,"fruit_strawberry":100,"fruit_orange":30}]
const result = fn(vegsAndFruits)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.min.js" integrity="sha512-t0vPcE8ynwIFovsylwUuLPIbdhDj6fav2prN9fEu/VYBupsmrmk9x43Hvnt+Mgn2h5YPSJOk7PMo9zIeGedD1A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
The pickby function takes two parameters, value and key.
You can run R.map(R.pickBy((_, key) => key.startsWith('fruit')),vegsAndFruits) to get the result you want.