0

is it possible to get a reference to an object with the object itself

obj

and the attributes in string form

'address.town.street'

so that at the end it resolves

obj.address.town.street

i could immageine smth like the eval() function.

3
  • 1
    noooo. Do not use eval! Commented Jan 22, 2014 at 16:22
  • any quick explanation why not to use it besides it is very slow? Commented Jan 22, 2014 at 16:36
  • In general bad practice, teaches bad habits when there are good alternatives (like this one) Commented Jan 22, 2014 at 16:37

2 Answers 2

3

Try

function getValue(obj, path) {
    return path.split(".").reduce(function(obj, name){ return obj[name]}, obj);
}
Sign up to request clarification or add additional context in comments.

4 Comments

Just remember that if any of your intermediate objects, say town is null or undefined, this will throw an exception. If you have to add null-checking it gets significantly more complicated.
@ScottSauyet 'more complicated'? Simple return obj&&obj[name] will almost do the trick. It will return false if path element was falsy.
@YuryTarabanko: You're absoultely right. It's not much more complicated. It won't necessarily return false, but that false-y value, but that's probably better anyway. This is so much simpler than approaches I've done (granted the problems were more complicated), but I thought the same null-checking issues would definitely rear their ugly heads here. Nicely done!
This is one-liner which allows You to go one step further - it returns particular falsy value (in this case null): path.split(".").reduce((obj, key) => obj && obj[key] || null, obj);
0

Do not use eval. Use this instead

Object.prototype.nestedByString=function(reference){
    var current=this;
    path=reference.split(".");
    for(var i=0;i<path.length;i++){
        current=current[path[i]];
    }
    return current;
}

Here is a demo

I suppose that if you're allergic to extending native prototypes, you can do this

function nestedByString(obj,reference){
        var current=obj;
        path=reference.split(".");
        for(var i=0;i<path.length;i++){
            current=current[path[i]];
        }
        return current;
}

10 Comments

Bad idea to spoil Object.prototype.
Why is it a bad idea? It was built into the language for a reason
Well, cos another developers don't give a heck what this method is for. And this code will potencially break for-in loops without .hasOwnProperty checking.
this doesn't use a for in loop
You can fix it in modern browsers by defining non-enumerable property. Object.defineProperty(Object.prototype, 'nestedByString', {value: function(){/*blah*/}, enumerable: false})
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.