在JSON中添加表示为字符串的数字

时间:2015-06-10 05:14:27

标签: javascript jquery

var x = {jason: ["2", "5"], alice: ["12", "35"], samuel: ["32", "132"]}

我正在尝试为每个键添加数字,所以我正在做

var out = 0;
    $.each(x, function (key, value) {
        out += key + ':';
        $.each(value, function (key, value) {
            out += parseInt(value, 10);
        });

    });

console.log(out)

这是我的小提琴 http://jsfiddle.net/sghoush1/1ezwwnm1/5/

将它们添加为字符串。所以我没有jason = 7,而是jason = 25等等 似乎无法弄清楚我做错了什么

11 个答案:

答案 0 :(得分:3)

将它们添加到字符串out时,您将它们重新转换为字符串。为防止这种情况,请将所有数字相加,然后将其附加到字符串中。

var out = "";
    $.each(x, function (key, value) {
        out += key + ':';
        var num = 0;
        $.each(value, function (key, value) {
            num += parseInt(value, 10);
        });
        out += num;
    });

console.log(out)

答案 1 :(得分:2)

循环显示keysreduce值:

//db = connect("localhost:27017/tecnicas")

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

diaFavorito = ["lunes", "martes", "miercoles", "sabado"]
sexo = ["hombre", "mujer"];
heladoFavorito = ["vainilla", "chocolate", "fresa", "coco"]

for(i = 0; i < 20; i++){
    print(db.usuarios.insert({
        fday: diaFavorito[getRandomInt(0, diaFavorito.length-1)],
        genero: sexo[getRandomInt(0, sexo.length-1)],
        fice: heladoFavorito[getRandomInt(0, heladoFavorito.length-1)],
        indice: i+1,
        ingresos: getRandomInt(12000, 120000)
    }))
}

// SECOND PART

paises = ["Mexico", "USA", "Portugal", "Nepal", "Argelia", "Chile"]
for(i = 0; i < 20; i++){
    numeroDePaisesVisitados = getRandomInt(1,6)
    var misPaisesVisitados = new Set(); // THE ERROR OCCURS HERE
    while(misPaisesVisitados.size != numeroDePaisesVisitados){
        misPaisesVisitados.add(
            paises[getRandomInt(0,paises.length-1)]
        )
    }
    var miArregloDePaisesVisitados = Array.from(misPaisesVisitados)
    print(db.usuarios.update(
        {indice:i+1},
        {$set: {paisesVisitados: miArregloDePaisesVisitados}}
    ))
}

答案 2 :(得分:1)

首先out0。只要向其中添加一个字符串(在本例中为key),它就会转换为字符串;之后你就会继续连接其他字符串。

您需要将为字符串输出保留的变量与为您计算总和的变量分开。这是对代码的最小修改:

var out = "";
$.each(x, function (key, value) {
    out += key + ':';
    var sum = 0;
    $.each(value, function (key, value) {
        sum += parseInt(value, 10);
    });
    out += sum + " ";
});
console.log(out);

更好的解决方案将涉及功能方法:

var out = Object.keys(x).map(function(key) {
  return key + ":" +
      x[key].reduce(function(a, b) { return a + parseInt(b, 10); }, 0);
}).join(' ');

答案 3 :(得分:1)

这会为您提供评论中要求的输出:

var x = {jason: ["2", "5"], alice: ["12", "35"], samuel: ["32", "132"]}


var out = {};
    $.each(x, function (key, value) {
        out[key] = 0;
        $.each(value, function (key2, value) {
            out[key] += parseInt(value, 10);
        });

    });

console.log(out)

答案 4 :(得分:0)

除了所有其他解决方案之外,您还可以使用.reduce()来计算总和。

var x = {
    jason: ["2", "5"],
    alice: ["12", "35"],
    samuel: ["32", "132"]
}

var out = {};
$.each(x, function (key, value) {
    out[key] = value.reduce(function (a, b) { return +a + +b; }); // <-- +a is same as parseInt(a, 10)
});

alert(JSON.stringify(out));

这是一个演示 http://jsfiddle.net/dhirajbodicherla/1ezwwnm1/14/

答案 5 :(得分:0)

您正在为字符串添加数字,将整数temp设为0,为其添加数字,然后将其添加回字符串

out =0
out+="key" 

转换为字符串

试试这个: -

var x = {jason: ["2", "5"], alice: ["12", "35"], samuel: ["32", "132"]}
var out = "";
    $.each(x, function (key, value) {
        out += key + ':';
        temp = 0;
        $.each(value, function (key, value) {
            temp += parseInt(value, 10);
        });
        out += temp;

    });

console.log(out)

http://jsfiddle.net/1ezwwnm1/8/

答案 6 :(得分:0)

尝试:

var x = {jason: ["2", "5"], alice: ["12", "35"], samuel: ["32", "132"]}
var out = '';
$.each(x, function (key, value) {
    var counter = 0;
    $.each(value, function (key1, value1) {
        counter += parseInt(value1, 10);
    });
    out += key + ':' + counter + ' ';
});

console.log(out)
//jason:7 alice:47 samuel:164

答案 7 :(得分:0)

您在示例中附加了字符串。我已更新your fiddle

    var x = {jason: ["2", "5"], alice: ["12", "35"], samuel: ["32", "132"]}


    var out = 0;
    $.each(x, function (key, value) {
        out += key + ':';
        var sum = 0;
        $.each(value, function (key, value) {
            sum += parseInt(value, 10);
        });
        out += sum;    
    });

答案 8 :(得分:0)

检查出来

var x = {jason: ["2", "5"], alice: ["12", "35"], samuel: ["32", "132"]};
var out = {};
for(var i in x){
    out[i] = parseInt(x[i][0])+parseInt(x[i][1]);
}
console.log(out);

答案 9 :(得分:0)

var x = {jason: ["2", "5"], alice: ["12", "35"], samuel: ["32", "132"]};
var str = 0;
$.each(x, function (key, value) {
    str += key + ':';
    var out = 0;
    $.each(value, function (key, value) {
        out += parseInt(value, 10);
    });
    str += out;
});
console.info(str);

var x = {jason: ["2", "5"], alice: ["12", "35"], samuel: ["32", "132"]}; var str = 0; $.each(x, function (key, value) { str += key + ':'; var out = 0; $.each(value, function (key, value) { out += parseInt(value, 10); }); str += out; }); console.info(str); 是你的设计?

答案 10 :(得分:0)

您要追加字符串中的所有值, 你需要获得总和然后将其附加到密钥。

var x = {jason: ["2", "5"], alice: ["12", "35"], samuel: ["32", "132"]}
        var out = '';
            $.each(x, function (key, value) {
                out += key + ':';
                var Keyvalue = 0;
                $.each(value, function (key, value) {
                    Keyvalue += parseInt(value, 10);
                });
               out += Keyvalue + " ";
            });

        console.log(out);

Fiddle here