0

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.

3
  • JSON is for converting an array or object to text, so you can send it over the network or put it into a file. It has nothing to do with converting one data structure into another data structure. Commented Dec 24, 2015 at 19:51
  • Thank you for your answers and comments. It was my mistake. Now I understand that I asked a wrong question. data, color, value etc. are parameters, not a string. So probably I am looking for a function that generates parameter-value combination from arrays and can be used in another function. Commented Dec 24, 2015 at 20:29
  • 1
    You have 3 answers that show how to do it. There's no built-in function that does this. Commented Dec 24, 2015 at 20:37

3 Answers 3

1

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/

Sign up to request clarification or add additional context in comments.

Comments

1

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().

Comments

1

This would do it:

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

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.