0

I want to parameterize my javascript routine so I can pass the field name that I want to use to populate from the list I've got back from my JSON interface. i.e, I want to convert my getRoutes() function (below) to getTable(), and pass the table name "Routes" and the field I want it to use, "routeId". "Routes" obviously isnt an issue as it's just passed to my JSON api, but how do I get "routeId" into the code ?. java has stuff like getDeclaredField, what's the javascript for that ?. I thought it was getValue, as in

    items.push("<option>" + val.getValue(keyName) + "</option>");

but that didnt work.

Here's my original working code that I want to generalise,

function getRoutes(){
    $.getJSON( "/GeeREST/Entity?entity=Routes", 
        function( data ) {
        var items = [];

        $.each( data, function( key, val ) {
            items.push("<option>" + val.routeId  + "</option>");
        });
    ...

And here's what I am trying to do

function getTable(tableName,keyName){
    $.getJSON( "/GeeREST/Entity?entity="+tableName, 
            function( data ) {
            var items = [];

            $.each( data, function( key, val ) {
                items.push("<option>" + val.getValue(keyName)  + "</option>");
            });
 ...
3
  • Is data[keyName] what you are looking for? Commented Feb 8, 2014 at 13:42
  • Not sure but I think the square brackets would do the trick. You can do var fieldname = "routeid"; var value = val[fieldname] . Is that what you are trying to do? Commented Feb 8, 2014 at 13:43
  • @Matt you busted me ;) Commented Feb 8, 2014 at 13:44

1 Answer 1

1

Here is a simple explanation:

var a = { 'b':1,'c':2};
$.each( a, function(key,val) {
   console.log(key,val,a[key]);
});
// Outputs:
// b 1 1
// c 2 2

So basically val is equal as a[key], and key is the key of the object we are iterating, So in your case you should use val[keyName].

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.