Simplest way to convert a JSON object to a newly structured JSON object?

I've got a JSON object that is structured like this:

    "xaxis": [
    "yaxis": [

From it I'd like to create another JSON object stuctured like this:

    "piegraph": [

Doing this conversion in client-side JavaScript would save me additional development and another server round-trip to fetch what is essentially the same data.

I can employ the jQuery library if that would help.


Assuming that your first JSON string is already parsed to an object, you just have to iterate over the elements of any of the two arrays, to build the result:

var result = { piegraph: [] }; // initialize piegraph as an empty array

var l = obj.xaxis.length;
while(l--) {
  result.piegraph[l] = [ obj.xaxis[l], obj.yaxis[l] ];

// result will look like this:
// {"piegraph":[["foo",333],["bar",992],["baz",1365]]}

No libraries needed, just a plain sequential loop. ;)

You could use Functional JavaScript:

second = { piegraph:[first.xaxis, first.yaxis]) };

Why can't you just use a for loop something like?

for(var i = 0; xaxis.length; i++){
  piegraph.push({xaxis[i], yaxis[i]);

This isn't hard to do manually, but the underscore.js functional library has a bunch of very handy functions, including .zip():

var piegraph = obj.xaxis, obj.yaxis );

Need Your Help

Why does the Graph API return question mark cover photos for my albums on first login and proper images on subsequent logins?

javascript facebook facebook-graph-api oauth facebook-javascript-sdk

I'm using the FB javascript driver for the Graph API to allow a user to pick photos from their Facebook account. The first time they connect they're prompted to login with: