3

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? ;)

1 Answer 1

4

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>';       
   });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.