CanCeylan
CanCeylan

Reputation: 3010

Modifying JSON Object with jQuery

My API responds my call with the following JSON structure:

[
    {
        "order": {
            "total": "240.0",
            "completed_at": 1358432545000
        }
    },
    {
        "order": {
            "total": "720.0",
            "completed_at": 1359474090000
        }
    }
]

However, I want this JSON to be structured like this in order to use my data in Flot Graphs:

   {
        "label":"Order",
        "dataBar":[
            [
                1358432545000,
                240.0
            ],
            [
                1325635200000 ,
                720.0
            ]
        ]
    }

I've tried the following code, but it returns all data with comma separated, without '[' and ']'

var flotData = $.map(API_Response, function(i){ return [i.order.completed_at, parseInt(i.order.total)] });

How should I do that?

Upvotes: 1

Views: 827

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382394

You can do this:

var data2 = {
    label: 'Order',
    dataBar: data.map(function(v){return [
         v.order.completed_at,
         parseFloat(v.order.total)
    ]})
};

Demonstration (open the console to see data2)

But please note there is nothing that can be called a "JSON structure" or a "JSON object".

What you have is a plain JavaScript object, even if it was sent to your browser encoded in JSON.


Now supposing you don't know the property of your object is called order, then you can do it with

var label;
for (var k in data[0]) {
   label = k[0].toUpperCase()+k.slice(1);
   break;
}
var data2 = {
    label: label,
    dataBar: data.map(function(v){return [
         v[k].completed_at,
         parseFloat(v[k].total)
    ]})
};

(It would be cleaner without support for IE 8, as I could have used Object.keys.)

Upvotes: 7

Related Questions