Iqbal Kabir
Iqbal Kabir

Reputation: 1610

JavaScript array into JSON data

I am not very comfortable in JavaScript. This question may be silly, but I could not find any suitable solution.

I have following two arrays.

colors = ['red',  'green',  'blue'];
values = [20, 50, 100];

Now I want to convert it into a data series, something like,

data: [{
    color:  'red',
    value:  20,
}, {
    color:  'green',
    value:  50,
}, {
    color:  'blue',
    value:  100,
}]

I looked JSON.stringify() and jQuery.param() functions, but not clear how to accomplish this.

Upvotes: 0

Views: 566

Answers (3)

Wesley Smith
Wesley Smith

Reputation: 19571

This would do it:

var data=[];
for(var i=0;i<colors.length;i++){
    data.push({color:colors[i], value:values[i]});
 }

Upvotes: 1

user5692355
user5692355

Reputation:

What you need is to combine the arrays, you could map the arrays using this snippet:

var jsonData =
{
  data: colors.map(function(color, index) {
          return ({ color: color, value: values[index]});
        })
};
var jsonStringified = JSON.stringify(jsonData);

What I've done here is to map the colors array into a new array containing the corresponding value (of the same index) and assigned it to object property data. The final object I converted to string using JSON.stringify().

Upvotes: 1

DinoMyte
DinoMyte

Reputation: 8868

In order to accomplish what you need, you need to create a new array that has elements from both colors and values, matched on their index and then apply JSON.stringify() to this new array to convert it into a string.

var colors = ['red',  'green',  'blue'];
var values = [20, 50, 100];

var data = [];
$.each(colors,function(i)
{
  data.push({'color' : colors[i], 'values' : values[i]});
});

var a = JSON.stringify(data);
alert(a);

Example : https://jsfiddle.net/DinoMyte/2s67pm8c/

Upvotes: 1

Related Questions