简体   繁体   English

javascript获取json内部值

[英]javascript get json inner value

Let's I have next object 我有下一个对象

   var o = { "foo" : {"bar" : "omg"} };  

I can get value of key foo using 我可以使用获取键foo

o["foo"] // return {"bar" : "omg"} 

and I can get value of key bar inside foo using 我可以使用以下方法获取foo的键bar

o["foo"]["bar"]  // return "omg"   

Can I get value of key bar inside foo using brackets [] single time. 我可以一次使用方括号[]获得foo内部的键bar值。
Somethong like 有点像

o["foo.bar"] // not working(

or 要么

o["foo/bar"] // not working(

It is fairly common to create a getter function to do something like this. 创建一个getter函数来完成类似的事情是很普遍的。 From the comment: 从评论:

I have object o and string 'foo.bar', and i want get "omg". 我有对象o和字符串'foo.bar',我想获取“ omg”。

var getProp = function (theObject, propString) {
    var current = theObject;
    var split = propString.split('.');

    for (var i = 0; i < split.length; i++) {
        if (current.hasOwnProperty(split[i])) {
            current = current[split[i]];
        }
    }

    return current;
};

http://jsfiddle.net/MXu2M/ http://jsfiddle.net/MXu2M/

Note: this is a thrown together example, you'd want to bullet proof and buff it up before dropping it on your site. 注意:这是一个拼凑在一起的示例,在将其放到您的网站上之前,您需要对其进行防弹和抛光。

不幸的是,您只能使用o["foo"]["bar"]o.foo.bar

No, you must use o["foo"]["bar"] because it's an object inside another object. 不,您必须使用o["foo"]["bar"]因为它是另一个对象中的一个对象。 If you want to access it with "foo.bar", it means you must create the first object like this: 如果要使用“ foo.bar”访问它,则意味着必须创建第一个对象,如下所示:

var o = {"foo.bar": "omg"}

o["foo.bar"] or o["foo/bar"] are not valid for your example. o["foo.bar"]o["foo/bar"]对于您的示例无效。 You could use this notation that is cleaner: 您可以使用更简洁的表示法:

var bar = o.foo.bar // bar will contain 'omg'

there is a way, but I'm not sure this is what you asked for: 有一种方法,但是我不确定这是您要的:

eval("o.foo.bar");

it is dangerous though, and doesn't use [] , but if what you want is to use a string for accessing any object it works 这样做很危险,并且不使用[] ,但是如果您要使用字符串访问任何对象,它将起作用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM