sqdejan
sqdejan

Reputation: 71

Parsing from JSON file to JavaScript in a specific order

I have the following function:

$(document).ready(function() {
    $('#container')
        .TidyTable({
            columnTitles : ['Name','Address','Age'],
            columnValues : [
                ['Dan','Daneroad 1','19'],
                ['Ann','Annroad',''],
            ]
        });
});

I have a JSON file with the following structure:

{ "results": [
    {
        "address" : "some address1"
        "age"   : "some age1"
        "name"  : "some name1"
    },
    {
        "address" : "some address2"
        "name"  : "some name2"
    }
]}

As you can see the order is alphabetic and not all objects contain the same amount of information. Can I create an array that will replace columnValues, with arrays that have key/values in the order I want, and if a key is not present replace it with an empty string? I imagine the array will look like this

[
  ['some name1', 'some address1', 'some age1'],
  ['some name2', 'some address2', '']
]

I am not that traversed in this area so please be specific thanks :)

Upvotes: 0

Views: 45

Answers (2)

Luan Castro
Luan Castro

Reputation: 1184

you can use the function in bellow...

   function objToColumnValues(results, headers){

       var values = results.map(function(resultItem){

           var row = [];
           headers.forEach(function(header){
               row.push(resultItem[header] || '' );
           });
           return row;
       });


       return values;
   }

you will use ...

   //in var json is your json-string

   var parsed = JSON.parse(json);
   var colValues = objToColumnValues(parsed.results, ['name', 'address', 'age']);

Upvotes: 0

Matt Burland
Matt Burland

Reputation: 45155

Assuming you already know the property names you are looking for (because I assume they match the column titles), you can simply do something like this:

var array = [];

for(var i=0; i < original.results.length; i++) {
    var subArray = [];
    subArray.push(original.results[i].name || "");
    subArray.push(original.results[i].address || "");
    subArray.push(original.results[i].age || "");
    array.push(subArray);
}

console.log(array);

Or, if you want to be more terse, you can do this in the body of the loop:

array.push([original.results[i].address || "",
           original.results[i].name || "",
           original.results[i].age || ""]);

If you don't know the properties of the objects in results then it's a little more tricky. You can use a for..in loop to loop over all the properties, but the order won't be guaranteed.

Upvotes: 1

Related Questions