简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM