Ramda.js-如何从嵌套数组查看许多值

问题描述 投票:0回答:4

我有此代码:

import {compose, view, lensProp, lensIndex, over, map} from "rambda";

let order = {
    lineItems:[
        {name:"A", total:33},
        {name:"B", total:123},
        {name:"C", total:777},
    ]
};

let lineItems = lensProp("lineItems");
let firstLineItem = lensIndex(0);
let total = lensProp("total");

我的目标是获得所有totals中的所有lineItems(因为我想对它们进行求和)。我这样逐步解决了这个问题:

console.log(view(lineItems, order)); // -> the entire lineItems array
console.log(view(compose(lineItems, firstLineItem), order)); // -> { name: 'A', total: 33 }
console.log(view(compose(lineItems, firstLineItem, total), order)); // -> 33

但是我无法找出正确的表达式来取回总计数组

console.log(view(?????, order)); // -> [33,123,777]

这是我的问题-?????在哪里?

我这样做是为了无知而编码:

let collector = [];
function collect(t) {
    collector.push(t);
}
over(lineItems, map(over(total, collect)), order);
console.log(collector); // -> [33,123,777]

但是我敢肯定,一个本地人知道如何做得更好。

ramda.js
4个回答
1
投票
您为什么要在这里使用镜片?不要误会我的意思;镜片很好,但是在您的情况下,它们似乎并没有增加太多价值。

最终,这是您尝试完成的任务(据我所知):

map(prop('total'), order.lineItems)

您可以使用:

const get_total = compose(map(prop('total')), propOr([], 'lineItems')); get_total(order);


1
投票
您可以使用R.pluck从对象数组中获取值数组:

1
投票
可以使用镜头(遍历)来实现,尽管可能不值得增加额外的复杂性。

0
投票
根据您对customcommander答案的评论,我认为您可以相当简单地编写它。我不知道如何接收模式,但是如果您可以将lineItems节点的路径转换为字符串数组,那么您可以编写一个相当简单的函数:
© www.soinside.com 2019 - 2024. All rights reserved.