0

Let's I have next object

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

I can get value of key foo using

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

and I can get value of key bar inside foo using

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

Can I get value of key bar inside foo using brackets [] single time.
Somethong like

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

or

o["foo/bar"] // not working(
5
  • whats wrong with o['foo']['bar'] or o.foo.bar? Commented Sep 13, 2012 at 12:42
  • 1
    No you can't do that , but you could do `o.foo.bar´ Commented Sep 13, 2012 at 12:42
  • Obviously you wouldn't ask it if you just need to get 'omg' yet another way, right? Do you need to find the name of the o.foo property (which would be bar), right? Commented Sep 13, 2012 at 12:43
  • I have path to inner element like string 'foo.bar', and I want get inner element by string Commented Sep 13, 2012 at 12:44
  • I have object o and string 'foo.bar', and i want get "omg". So I can't use o.foo.bar Commented Sep 13, 2012 at 12:45

5 Answers 5

3

It is fairly common to create a getter function to do something like this. From the comment:

I have object o and string 'foo.bar', and i want get "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/

Note: this is a thrown together example, you'd want to bullet proof and buff it up before dropping it on your site.

Sign up to request clarification or add additional context in comments.

Comments

0

No, you must use o["foo"]["bar"] because it's an object inside another object. If you want to access it with "foo.bar", it means you must create the first object like this:

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

Comments

0

o["foo.bar"] or o["foo/bar"] are not valid for your example. You could use this notation that is cleaner:

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

Comments

0

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

Comments

0

Unfortunately, you can only use o["foo"]["bar"] or o.foo.bar

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.