我有一个对象数组,每个对象都有一些事务集合,我需要提取数组的两个值
[
{
"id": "1",
"value": 2343,
"transactions": [
{
"id": 88,
"amount": 34,
},
{
"id": 89,
"amount": 111,
}
]
},
{
"id": "2",
"value": 345,
"transactions": [
{
"id": 90,
"amount": 44,
},
{
"id": 91,
"amount": 112,
}
]
}
]
我通过
实现的第一个objects.reduce((acc, transaction) => acc + transaction.value, 0);
但第二个对我来说太困难了;我循环并减少每个对象?
答案 0 :(得分:3)
使用lodash,您可以使用_.sumBy()
获取值,并嵌套_.sumBy()
调用以获取交易金额:
const data = [{"id":"1","value":2343,"transactions":[{"id":88,"amount":34},{"id":89,"amount":111}]},{"id":"2","value":345,"transactions":[{"id":90,"amount":44},{"id":91,"amount":112}]}];
const value = _.sumBy(data, 'value');
const transactions = _.sumBy(data, ({ transactions }) => _.sumBy(transactions, 'amount'));
console.log('value: ', value);
console.log('transactions: ', transactions);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
&#13;
如果没有lodash,您可以使用与Array#reduce相同的逻辑:
const data = [{"id":"1","value":2343,"transactions":[{"id":88,"amount":34},{"id":89,"amount":111}]},{"id":"2","value":345,"transactions":[{"id":90,"amount":44},{"id":91,"amount":112}]}];
const value = data.reduce((acc, { value }) => acc + value, 0);
const transactions = data.reduce((acc, { transactions }) =>
transactions.reduce((acc, { amount }) => acc + amount, 0)
, 0);
console.log('value: ', value);
console.log('transactions: ', transactions);
&#13;
答案 1 :(得分:0)
这可能是老式的,但我喜欢> powell <- solnp(x0, fun = fn1, eqfun = eqn1, eqB = c(10, 0, -1),
+ control = list(trace = 0))>
> # look, no output
循环来解决像这样的简单问题。它们简单明了,易于理解。
.forEach()
&#13;