Reputation: 175
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"}
]}
Upvotes: 0
Views: 52
Reputation: 51
var result = {'names' : names.map(function(val, ind) { var elem = {}; elem[val] = this['values' + ++ind].toString(); return elem; }) };
Upvotes: 0
Reputation: 386670
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.
Upvotes: 1
Reputation: 3200
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);
}
Upvotes: 1
Reputation: 5629
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));
Upvotes: 1