添加对象数组中包含的值

时间:2016-07-28 10:59:22

标签: javascript jquery

我如何在对象中添加所有值?

例如amoutpay": ["4222","1000"]会给我5222

这是我的目标:

{
    "amoutpay": [ "4222", "1000" ],
    "amtpending": [ "778", "4000" ],
    "totalcost": [ "5000", "5000" ],
    "coursename": [ "Office Automation", "ajaba" ]
}

我想要的是将值添加到变量中。我会使用拆分吗?

var a =
var b =
var c =

3 个答案:

答案 0 :(得分:4)

您可以使用Array.prototype.reduce(),如下所示:



var obj = {
    "amoutpay": [ "4222", "1000" ],
    "amtpending": [ "778", "4000" ],
    "totalcost": [ "5000", "5000" ],
    "coursename": [ "Office Automation", "ajaba" ]
},
    
    a = obj.amoutpay.reduce(function(prevVal, curVal, curInd) {
        return +prevVal + +curVal;
    }),
    b = obj.amtpending.reduce(function(prevVal, curVal, curInd) {
        return +prevVal + +curVal;
    }),
    c = obj.totalcost.reduce(function(prevVal, curVal, curInd) {
        return +prevVal + +curVal;
    });

console.log( a, b, c );




或者您可以更进一步定义自己的数组方法,例如Array.prototype.sum()



var obj = {
        "amoutpay": [ "4222", "1000" ],
        "amtpending": [ "778", "4000" ],
        "totalcost": [ "5000", "5000" ],
        "coursename": [ "Office Automation", "ajaba" ]
    };

Array.prototype.sum = function() {
    return this.reduce(function( prv, cur, ind ) {
        return +prv + +cur;
    });
};

var a = obj.amoutpay.sum(),
    b = obj.amtpending.sum(),
    c = obj.totalcost.sum();

console.log( a, b, c );




答案 1 :(得分:2)

var obj = {
    "amoutpay": [ "4222", "1000" ],
    "amtpending": [ "778", "4000" ],
    "totalcost": [ "5000", "5000" ],
    "coursename": [ "Office Automation", "ajaba" ]
}

var a = addValues(obj.amoutpay);

function addValues(arr) {
    return arr.map(function(el) {
        return Number(el);
    }).reduce(function(prev, curr){
        return prev + curr;
    })
}

答案 2 :(得分:1)

我们迭代对象元素,对于所有数组,我们检查所有元素是否都是数字。如果是,则将它们作为变量添加到window对象,因此在循环之后,我们将为问题中显示的输入提供amoutpay变量。请注意,如果key恰好已经是变量,则此代码将覆盖它。

for (var key in obj) {
    if (Array.isArray(obj[key])) {
        var shouldAdd = true;
        for (var index = 0; shouldAdd && index < obj[key].length; index++) {
            if (isNaN(obj[key][index])) {
                shouldAdd = false;
            }
        }
        if (shouldAdd) {
            window[key] = 0;
            for (var index = 0; index < obj[key].length; index++) {
                window[key] += parseFloat(obj[key][index]);
            }
        }
    }
}