0

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.

1
  • While the answer below technically answers this question specifically I'd like to point out that this is really very basic javascript. I strongly suggest that you actually learn javascript before trying to tackle something like this. This question is like someone writing code in C and asking how to get the value form a pointer Commented Mar 14, 2013 at 6:57

1 Answer 1

2

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
    });
}
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.