我有此代码:
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]
但是我敢肯定,一个本地人知道如何做得更好。
最终,这是您尝试完成的任务(据我所知):
map(prop('total'), order.lineItems)
您可以使用:
const get_total = compose(map(prop('total')), propOr([], 'lineItems')); get_total(order);
lineItems
节点的路径转换为字符串数组,那么您可以编写一个相当简单的函数: