Search code examples
javascriptjqueryjsonjavascript-framework

Easiest way to interate over a complex JSON object via Javascript


I'm consuming JSON data that has a bit of a weird structure for example:

{
    "RESULT": 
    {
        "COLUMNS": ["ID","name","ENABLED","perms","vcenabled","vcvalue","checkenabled","checkvalue","indxenabled","indxvalue"],
        "DATA": [
                    [7,"Site-A", 1, "1,2", 1, 1, 1, 0, 0, 0],
                    [15,"Site-B", 1, "1,2,3,4", 1, 1, 1, 0, 0, 0]
        ]
    },
    "ERROR": 0
}

I would like to create some JavaScript that would restructure this data to proper JSON structures so that the "Column" array values become the keys for the "DATA" array's values. So after a JS process is run the data resembles the following:

[
  {"ID":7,"name":"Site-A","ENABLED":1,"perms":"1,2","vcenabled":1,"vcvalue":1,"checkenabled":1,"checkvalue":1,"indxenabled":1,"indxvalue":1},
  {"ID":15,"name":"Site-B","ENABLED":1,"perms":"1,2","vcenabled":1,"vcvalue":1,"checkenabled":1,"checkvalue":1,"indxenabled":1,"indxvalue":1}

]

What are the JavaScript best practices for accomplishing the JSON restructuring? Could I accomplish this task using a JS framework like JQuery, Foundation JS, ect... ?


Solution

  • newjson is your new object, j is your json,

    code is very fast as it caches the legth and don't uses push.

    And as it's pure javascript it's faster than all the libraries.

    var j={
     "RESULT":{
      "COLUMNS":[
       "ID",
       "name",
       "ENABLED",
       "perms",
       "vcenabled",
       "vcvalue",
       "checkenabled",
       "checkvalue",
       "indxenabled",
       "indxvalue"
      ],
      "DATA":[
       [7,"Site-A", 1, "1,2", 1, 1, 1, 0, 0, 0],
       [15,"Site-B", 1, "1,2,3,4", 1, 1, 1, 0, 0, 0]
      ]
     },
     "ERROR": 0
    }
    
    var newjson=[],d=j.RESULT.COLUMNS.length;
    for(var a=0,b=j.RESULT.DATA.length;a<b;a++){
     for(var c=0,tmpObj={};c<d;c++){
      tmpObj[j.RESULT.COLUMNS[c]]=j.RESULT.DATA[a][c];
     }
     newjson[a]=tmpObj;
    }
    
    console.log(newjson);
    

    based on Bergi's response u can also use the while-- loop.

    var orig={
     "RESULT":{
      "COLUMNS":[
       "ID",
       "name",
       "ENABLED",
       "perms",
       "vcenabled",
       "vcvalue",
       "checkenabled",
       "checkvalue",
       "indxenabled",
       "indxvalue"
      ],
      "DATA":[
       [7,"Site-A", 1, "1,2", 1, 1, 1, 0, 0, 0],
       [15,"Site-B", 1, "1,2,3,4", 1, 1, 1, 0, 0, 0]
      ]
     },
     "ERROR": 0
    }
    
    var formatted = [],
    data = orig.RESULT.DATA,
    cols = orig.RESULT.COLUMNS,
    l = cols.length,
    f = data.length;
    
    while (f--) {
      var d = data[f],
          o = {},
          g = l;
      while (g--) {
        o[cols[g]] = d[g];
      }
      formatted[f] = o;
    }