如何使用 ramda 过滤对象条目以仅保留其键以字符串开头的条目?

How to filter object entries to keep only those whose keys start with a string, using ramda?

具有以下数组:

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
    }
]

我想将它过滤到 return 同一个数组 但是 只保留以 "fruit".

开头的属性

预期输出

const expectedOutput = [
    {
        "fruit_banana": 10,
        "fruit_apple": 1,
        "fruit_watermelon": 11
    },
    {
        "fruit_apricot": 22
    },
    {
        "fruit_strawberry": 100,
        "fruit_orange": 30
    }
]

我的尝试

我认为解决方案应该来自混合 ramda 的 R.startsWith()R.pickBy()。但以下内容并不像我预期的那样有效:

const R = require("ramda")

R.map(R.pickBy(R.startsWith(["fruit"])),vegsAndFruits)

哪个return

// [ {}, {}, {} ]

我在这里错过了什么?

R.pickBy 谓词使用 value(第一个)和 key(第二个)参数调用。由于您需要 key,因此使用 R.nthArg 创建一个函数 returns 第二个参数:

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>

pickby 函数有两个参数,value 和 key。

您可以运行R.map(R.pickBy((_, key) => key.startsWith('fruit')),vegsAndFruits)得到您想要的结果。