有三个数组,
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"}
]}
答案 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)
var result = {'names' : names.map(function(val, ind) { var elem = {}; elem[val] = this['values' + ++ind].toString(); return elem; }) };
&#13;