添加数组的值存储为对象的属性

时间:2015-06-10 22:52:54

标签: javascript

我有一个看起来像这样的数组

var x = [
    {
        "name" : "Paris",
        "count" : [1,30, 20]
    },{
        "name" : "London",
        "count" : [5,30, 10]
    }
]

我试图通过添加属性的数字来解决这个问题" count"

var y = [
    {
        "name" : "Paris",
        "count" : 51
    },{
        "name" : "London",
        "count" : 45
    }
]

这是我的代码

var y = []
function doTotal(x, i){
    var out = 0;
    for(var j = 0; j < x[i].count.length; j++){
        out += x[i].count[j];
    }
}
for(var i = 0; i < x.length; i++){
    y[i] = {
        name : x[i].name,
        total : doTotal(x, i)
    }
}

console.log(y)

..总数未定义。我做错了什么?

1 个答案:

答案 0 :(得分:2)

您需要在out函数

中返回变量dototal

&#13;
&#13;
var x = [
    {
        "name" : "Paris",
        "count" : [1,30, 20]
    },{
        "name" : "London",
        "count" : [5,30, 10]
    }
]
var y = [
    {
        "name" : "Paris",
        "count" : 51
    },{
        "name" : "London",
        "count" : 45
    }
]
function doTotal(x, i){
    var out = 0;
    for(var j = 0; j < x[i].count.length; j++){
        out += x[i].count[j];
    }
    return out;
}
for(var i = 0; i < x.length; i++){
    y[i] = {
        name : x[i].name,
        total : doTotal(x, i)
    }
}
alert(JSON.stringify(y));
&#13;
&#13;
&#13;