0

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?

3 Answers 3

2

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.

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

Comments

1

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

1 Comment

@Mohan in the interest of learning could you please explain why you unaccepted my answer? Is there a bug in this code?
0

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

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.