[英]Storing array as a key pair in a json using javascript?
There are three arrays , 一共有三个数组,
var names = ["Increment","Decrement"]
var values1 = [1,2,3,4,5,6]
var values2 = [7,8,9,10,11]
Now i would like to construct a json like 现在我想构造一个像
{"names":[
{"Increment":"1,2,3,4,5,6"},
{"Decrement":"7,8,9,10,11"}
]}
Create an empty object and change it's properties. 创建一个空对象并更改其属性。
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));
You can do it with something like this: 您可以使用以下方法进行操作:
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);
}
I suggest to change the data structure to a more compact style. 我建议将数据结构更改为更紧凑的样式。
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;
Result: 结果:
{
Increment: [1, 2, 3, 4, 5, 6],
Decrement: [7, 8, 9, 10, 11]
}
To generate a JSON, you may convert it with JSON.stringify()
to a string. 要生成JSON,您可以使用JSON.stringify()
将其转换为字符串。
var result = {'names' : names.map(function(val, ind) { var elem = {}; elem[val] = this['values' + ++ind].toString(); return elem; }) };
\n
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.