views:

295

answers:

2

I have the following JSON:

var json = { "system" : { "world" : { "actions" : { "hello" : { "src" : "hello world/hello world.js", "command" : "helloWorld" } } } } }

I have the following javascript:

var x = "system";
// get the contents of system by doing something like json.getElementByName(x)

How do I get the contents of system using json and x in jQuery?

+2  A: 

Well to my knowledge jQuery doesn't navigate arbitrary objects like that - just the DOM. You could write a little function to do it:

function findSomething(object, name) {
  if (name in object) return object[name];
  for (key in object) {
    if ((typeof (object[key])) == 'object') {
      var t = findSomething(object[key], name);
      if (t) return t;
    }
  }
  return null;
}

It should be obvious that I haven't put that function through an elaborate QA process.

Pointy
+2  A: 

Just use:

var x = "system";
json[x];

It is a key/value system of retrieval, and doesn't need a function call to use it.

Doug Neiner
Yes that works unless the label corresponding to the value of "x" is buried deep in the jungle of substructure dangling off the "json" object.
Pointy
Perhaps a better example of what you need is `x = "hello"` ? You might want to update your question to reflect that.
Doug Neiner