user1065490
user1065490

Reputation: 305

Using string variable as a json object name

I have a dynamic string variable created by UI (valkey in below code) and I want to use that variable as a JSON key to get a value from TestObj which is a JSON object. But an attempt with the following code has returned an error.

 var valkey=$('#cityfrm').val()+"_TO_"+$('#cityto').val();

 if($('#cityfrm').val()!="NIL" || $('#cityto').val()!="NIL")   
   {

    $.each(TestObj.valkey, function() { 
        var durn=this.duration;
        var prc=this.price;
        var curlegs=this.legs;
        // updating ui
     });
   }

I appreciate any help.

Upvotes: 0

Views: 347

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

TestObj.valkey will look for the key valkey in TestObj, which is undefined in your case that is why you are getting the error.

If you want to look for a key from a variable you need to use the syntax TestObj[valkey].

Ex:

var valkey=$('#cityfrm').val()+"_TO_"+$('#cityto').val();

if($('#cityfrm').val()!="NIL" || $('#cityto').val()!="NIL") {
    $.each(TestObj[valkey], function() { 
        var durn=this.duration;
        var prc=this.price;
        var curlegs=this.legs;
        // updating ui
    });
}

Upvotes: 2

Related Questions