Question

I have a json object {"yAxis" : { "Batting" : [10, 20, 30, 40] , "Bowling" : [10, 30, 50, 70], "Fielding" : [20, 40, 50, 70] } },

and want to convert to json array like this

[ { "name": "Batting" ,"data": [10,20,30,40]} , { "name": "Bowling" ,"data": [10,30,50,70] },{ "name": "Fielding" ,"data": [20,40,50,70]}] 

I can create json object for each index but how can i put those to json array?

for(var abc in objJSON.yAxis)
{

    seriesValues +=  JSON.stringify({name:abc,data:(objJSON.yAxis)[abc]});
}

Any help?

Was it helpful?

Solution

You're close:

var seriesValues = [];
for (var abc in objJSON.yAxis) {
  seriesValues.push({name: abc, data: objJSON.yAxis[abc]});
}

That will make a javascript array. If you need it as a JSON string then append:

var myString = JSON.stringify(seriesValues);

OTHER TIPS

You can just loop through creating the object, don't worry about stringifying it.

var obj = {"yAxis" : { "Batting" : [10, 20, 30, 40] , "Bowling" : [10, 30, 50, 70], "Fielding" : [20, 40, 50, 70] } };

var keys = Object.keys(obj.yAxis),
    narray = [];
keys.forEach(function(v) {
    narray.push({ "name": v, "data": obj.yAxis[v] });
});

Then, if you need to stringify it, you can simply do a JSON.stringify(narray) later on.

Simply stringify after the array generated all around.

var result = [];

for(var name in objJSON.yAxis)
{
    result.push({name: name, data: objJSON.yAxis[name]});
}

return JSON.stringify(result);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top