Skip to content

Transform JSON Object to another – Format It

i want to transform a json formated output to another. How i can do this ?

Example: Old json

"data": 
[
    {
        "id" : "e49e183e-9325-4e62-8eda-7e63fb7cdbbd",
        "name" : "test"
    },
    {
        "id" : "ac310894-d808-447b-a189-d07edb7f6dd7",
        "name" : "test2"
    }
]

New Json which i want without braces only like this with bracket

"aaData": 
[ 
    [
        "e49e183e-9325-4e62-8eda-7e63fb7cdbbd","test"
    ],
    [
        "ac310894-d808-447b-a189-d07edb7f6dd7","test2"
    ]
] 

Answer

You could just loop through the items and push them into a new object:

var len = old.data.length,
    newData = {aaData:[]},
    i;

for ( i=0; i < len; i+=1 ) {
    newData.aaData.push( [ old.data[ i ].id, old.data[ i ].name] );   
}

example: https://jsfiddle.net/q2Jzb/1/

You are presumably passing these to DataTables (as you use the name aaData), note that DataTables takes an object as the configuration, it’s not the same as JSON.