0

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"}
]}
3
  • what is the data type of increment? and why do you want to get an array with objects instead of an object with properties? Commented Nov 3, 2015 at 12:00
  • 1
    @Sarath, why the edit of the wanted result? Commented Nov 3, 2015 at 12:11
  • @nina yes..the user2860954 denotes explanation and un-formated array.. as his result and asking for json.. Commented Nov 3, 2015 at 12:15

4 Answers 4

1

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));
Sign up to request clarification or add additional context in comments.

Comments

1

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);
}

Comments

1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.