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
jQuery and JSON: getting an element by name
提问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 json
and x
in jQuery?
如何在 jQuery 中使用json
和获取系统内容x
?
回答by Doug Neiner
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.
它是一个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 流程来完成该功能。