Get json value using string

Say 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 a json object and build a string using only the specified columns.

guess the game:

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

Can someone show me the working code ?;)

+3
source share
1 answer

Just use jsonValue [columnName] instead of jsonValue.attr (columnName). In JavaScript, obj [key] allows you to 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>';       
   });
});
+4
source

Source: https://habr.com/ru/post/1770531/


All Articles