使用javascript将数组存储为json中的密钥对?

时间:2015-11-03 11:50:36

标签: javascript json

有三个数组,

var names = ["Increment","Decrement"]
var values1 = [1,2,3,4,5,6] 
var values2 = [7,8,9,10,11]

现在我想构建一个类似

的json
{"names":[
    {"Increment":"1,2,3,4,5,6"},
    {"Decrement":"7,8,9,10,11"}
]}

4 个答案:

答案 0 :(得分:1)

创建一个空对象并更改它的属性。

var names = ["Increment","Decrement"];
var values1 = [1,2,3,4,5,6];
var values2 = [7,8,9,10,11];

var json = [{}];

 json[0].Increment = values1.toString();
 json[0].Decrement = values2.toString();

console.log(JSON.stringify(json));

答案 1 :(得分:1)

你可以这样做:

var names = ["Increment","Decrement"];
var values1 = [1,2,3,4,5,6];
var values2 = [7,8,9,10,11];

var yourArray = [];

for ( var i = 0, len = names.length; i < len; i++ ) {
    o = {};
    o[names[i]] = windows['values'+ i].join(',');
    yourArray.push(o);
}

答案 2 :(得分:1)

我建议将数据结构更改为更紧凑的样式。

var names = ["Increment", "Decrement"],
    values1 = [1, 2, 3, 4, 5, 6],
    values2 = [7, 8, 9, 10, 11],
    obj = {};

obj[names[0]] = values1;
obj[names[1]] = values2;

结果:

{
    Increment: [1, 2, 3, 4, 5, 6],
    Decrement: [7, 8, 9, 10, 11]
}

要生成JSON,您可以使用JSON.stringify()将其转换为字符串。

答案 3 :(得分:0)

&#13;
&#13;
var result = {'names' : names.map(function(val, ind) { var elem = {}; elem[val] = this['values' +   ++ind].toString(); return elem; }) };
&#13;
&#13;
&#13;