jQuery and JSON: getting an element by name

32,866

Solution 1

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.

Solution 2

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.

Solution 3

Try using JSON Path, it is like XPath expression.

Share:
32,866
Chetan
Author by

Chetan

Generalist software engineer with 10 years of experience shipping products featured by Apple and Google, ranging from full-stack mobile and web development, game development, UI / UX design, and AI / machine learning.

Updated on July 14, 2022

Comments

  • Chetan
    Chetan almost 2 years

    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?

  • Pointy
    Pointy about 14 years
    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.
  • Doug Neiner
    Doug Neiner about 14 years
    Perhaps a better example of what you need is x = "hello" ? You might want to update your question to reflect that.
  • lyolikaa
    lyolikaa over 3 years
    Should check for null on 'object' ... if (object[key] && (typeof (object[key])) == 'object' ) ...