0

I trying to build a JavaScript function which will grab a JSON encoded array and return a value based on the requested key. I use the jQuery $.parseJSON() method to take the JSON string and convert it into a JavaScript object. Here a watered down example:

function getValue(dynamicArrayKey) {
  var theArray = $.parseJSON(/* Get some JSON from a source using jQuery */);

  alert('Here is the value: ' + theArray.dynamicArrayKey);
}

So the key I want will be given to the function, and it should return the resulting value. I am thinking that the JavaScript eval() method should be used in there somewhere, but I'm not sure. Any help would be greatly appreciated.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Oliver Spryn
  • 16,871
  • 33
  • 101
  • 195

2 Answers2

4

There's no need to eval(), use

alert('Here is the value: ' + theArray[dynamicArrayKey]);
Dr.Molle
  • 116,463
  • 16
  • 195
  • 201
  • Awesome! Works like a charm! I was wondering, though, why can I do something like this: "theArray.notDynamicArrayKay", when I'm actually looking for a key by that name, but I have to use the "theArray[dynamicArrayKey]" when the value I'm looking for a value that is dynamic? Just curious. – Oliver Spryn Apr 11 '11 at 22:51
  • 1
    It's called subscript notation. You may take a look at http://www.crockford.com/misty/objects.html :) – Dr.Molle Apr 11 '11 at 23:03
0

Take a look at this. It may help.

How to search JSON tree with jQuery

Community
  • 1
  • 1
Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
  • Thanks for the pointer, but I'm afraid that would involve too much redundant processing for a simple task, especially since this function will be called rather frequently. – Oliver Spryn Apr 11 '11 at 22:55