jquery – Get json value by using a string – Education Career Blog

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? 😉

,

Just use jsonValuecolumnName instead of jsonValue.attr(columnName). In JavaScript objkey 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>' + jsonValuecolumnName + '</td>';       
   });
});

Leave a Comment