tags:

views:

39

answers:

1

Let's say that I got the following json object:

var jsonResult = {
    "result": [
         { "UserName": "joga", "FirstName": "Jonas", "LastName": "G" }
         { "UserName": "sss", "FirstName": "Abra", "LastName": "p" }
    ]
};

I got an array with:

var cols = ["UserName", "LastName"];

how do I go through the json object and build a string only using the specified columns.

guessing game:

var rows = '<tr>';
$.each(jsonResult.result, function(jsonKey, jsonValue) { 
   $.each(cols, function(i,columnName) {
     rows += '<td>' + jsonValue.attr(columnName) + '</td>';       
   });
});

Can anyone show me working code? ;)

+2  A: 

Just use jsonValue[columnName] instead of jsonValue.attr(columnName). In JavaScript obj[key] lets you access a property with a variable.

var jsonResult = {
    "result": [
         { "UserName": "joga", "FirstName": "Jonas", "LastName": "G" },
         { "UserName": "sss", "FirstName": "Abra", "LastName": "p" }
    ]
};

var cols = ["UserName", "LastName"];

var rows = '<tr>';
$.each(jsonResult.result, function(jsonKey, jsonValue) { 
   $.each(cols, function(i, columnName) {
     rows += '<td>' + jsonValue[columnName] + '</td>';       
   });
});
Arrix