jQuery 和 JSON:按名称获取元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2240665/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:05:16  来源:igfitidea点击:

jQuery and JSON: getting an element by name

jqueryjsontraversalgetelementsbyname

提问by Chetan

I have the following JSON:

我有以下 JSON:

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

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

I have the following javascript:

我有以下 javascript:

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

var x = "系统";
// 通过执行类似 json.getElementByName(x) 的操作来获取系统的内容

How do I get the contents of system using jsonand xin jQuery?

如何在 jQuery 中使用json和获取系统内容x

回答by Doug Neiner

Just use:

只需使用:

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

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

它是一个key/value检索系统,不需要函数调用来使用它。

回答by Pointy

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

就我所知,jQuery 不会像那样导航任意对象 - 只是 DOM。你可以写一个小函数来做到这一点:

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.

很明显,我还没有通过精心设计的 QA 流程来完成该功能。

回答by Muhammad Soliman

Try using JSON Path, it is like XPath expression.

尝试使用JSON Path,它就像 XPath 表达式。