MohanRajNK
MohanRajNK

Reputation: 895

convert json object to specific json array

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?

Upvotes: 0

Views: 181

Answers (3)

David Atchley
David Atchley

Reputation: 1204

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.

Upvotes: 2

Alfred Huang
Alfred Huang

Reputation: 18265

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

Upvotes: 0

James
James

Reputation: 22246

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

Upvotes: 1

Related Questions