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.

2 Answers 2

4

There's no need to eval(), use

alert('Here is the value: ' + theArray[dynamicArrayKey]);
Sign up to request clarification or add additional context in comments.

2 Comments

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.
It's called subscript notation. You may take a look at crockford.com/misty/objects.html :)
0

Take a look at this. It may help.

How to search JSON tree with jQuery

1 Comment

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.

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.