我可以使这个功能更简洁

时间:2016-11-10 13:39:31

标签: javascript

我有这个javascript片段,我想知道我是否可以在amount函数的一次传递中计算usersreduce

root.children.forEach(function(v) {

    v.amount = v.children.reduce(function(a, b) {
        console.log(a);
        return {
            amount: a.amount + b.amount
        }
    }, {
        'amount': 0
    }).amount

    v.users = v.children.reduce(function(a, b) {
        console.log(a);
        return {
            users: a.users + b.users
        }
    }, {
        'users': 0
    }).users

})

3 个答案:

答案 0 :(得分:6)

是的,你可以像下面这样做,

root.children.forEach(function(v) {
    var obj = v.children.reduce(function(a, b) {
        a.amount += b.amount;
        a.users += a.users;
    }, {'amount': 0, 'users' : 0 });
    v.amount = obj.amount;
    v.users = obj.users;
});

答案 1 :(得分:6)

看起来您可以将两种方法合二为一:

root.children.forEach(function(v) {        
    var result = v.children.reduce(
        function(a, b) {
            return {
                amount: a.amount + b.amount,
                users: a.users + b.users
            };
        },
        { amount: 0, users: 0 }
    ); // ^ Note that I left out the quotes there. In this case, they're optional.

    v.amount = result.amount;
    v.users= result.users;
});

答案 2 :(得分:1)

你可以进行一次Array#forEach循环。

var root = {
        children: [
            { children: [
                { amount: 2, users: 3 },
                { amount: 7, users: 5 }
            ]}
        ]
    };

root.children.forEach(function(v) {
    v.amount = 0;
    v.users = 0;

    v.children.forEach(function(a) {
        v.amount += a.amount;
        v.users += a.users;
    });
});
console.log(root);
.as-console-wrapper { max-height: 100% !important; top: 0; }