Ramda:如何根据嵌套数组中的值进行过滤
Ramda: How to filter based on a value in a nested array
我正在尝试以功能方式(使用 Ramda)完成此操作。我的 JSON 结构如下
[
{username: 'bob', age: 30, tags: ['work', 'boring']},
{username: 'jim', age: 25, tags: ['home', 'fun']},
{username: 'jane', age: 30, tags: ['vacation', 'fun']}
]
我正在尝试根据 'tags' 属性 中的值进行过滤,但没有成功。我能够过滤 ints/strings(年龄和用户名),但我无法弄清楚如何使用嵌套数组(标签)中的值进行过滤。任何帮助将不胜感激。
有很多方法可以做到这一点。但我认为最干净的是:
R.filter(R.where({tags: R.includes('fun')}))
您可以在 Ramda REPL.
中看到它的实际效果
其他选项,特别是如果字段嵌套更深时是compose
(或pipe
)prop
或path
调用contains
或可能要利用镜头。
不过,我认为上面的答案是最可读的。
const arr = [
{username: 'bob', age: 30, tags: ['work', 'boring']},
{username: 'jim', age: 25, tags: ['home', 'fun']},
{username: 'jane', age: 30, tags: ['vacation', 'fun']}
];
res = R.filter(R.where({tags: R.contains('home')}), arr);
我正在尝试以功能方式(使用 Ramda)完成此操作。我的 JSON 结构如下
[
{username: 'bob', age: 30, tags: ['work', 'boring']},
{username: 'jim', age: 25, tags: ['home', 'fun']},
{username: 'jane', age: 30, tags: ['vacation', 'fun']}
]
我正在尝试根据 'tags' 属性 中的值进行过滤,但没有成功。我能够过滤 ints/strings(年龄和用户名),但我无法弄清楚如何使用嵌套数组(标签)中的值进行过滤。任何帮助将不胜感激。
有很多方法可以做到这一点。但我认为最干净的是:
R.filter(R.where({tags: R.includes('fun')}))
您可以在 Ramda REPL.
中看到它的实际效果其他选项,特别是如果字段嵌套更深时是compose
(或pipe
)prop
或path
调用contains
或可能要利用镜头。
不过,我认为上面的答案是最可读的。
const arr = [
{username: 'bob', age: 30, tags: ['work', 'boring']},
{username: 'jim', age: 25, tags: ['home', 'fun']},
{username: 'jane', age: 30, tags: ['vacation', 'fun']}
];
res = R.filter(R.where({tags: R.contains('home')}), arr);