JavaScript对象数组的子集合中的属性和

时间:2018-01-21 00:02:11

标签: javascript lodash

我有一个对象数组,每个对象都有一些事务集合,我需要提取数组的两个值

  • 所有对象的总和值
  • 所有交易的总金额
[
    {
        "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);

但第二个对我来说太困难了;我循环并减少每个对象?

2 个答案:

答案 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;
&#13;
&#13;

如果没有lodash,您可以使用与Array#reduce相同的逻辑:

&#13;
&#13;
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;
&#13;
&#13;

答案 1 :(得分:0)

这可能是老式的,但我喜欢> powell <- solnp(x0, fun = fn1, eqfun = eqn1, eqB = c(10, 0, -1), + control = list(trace = 0))> > # look, no output 循环来解决像这样的简单问题。它们简单明了,易于理解。

&#13;
&#13;
.forEach()
&#13;
&#13;
&#13;