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.

alknows
  • 1,972
  • 3
  • 22
  • 26

2 Answers2

3

Try

function getValue(obj, path) {
    return path.split(".").reduce(function(obj, name){ return obj[name]}, obj);
}
Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98
  • 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. – Scott Sauyet Jan 22 '14 at 17:05
  • @ScottSauyet 'more complicated'? Simple `return obj&&obj[name]` will almost do the trick. It will return false if path element was falsy. – Yury Tarabanko Jan 23 '14 at 06:28
  • @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! – Scott Sauyet Jan 23 '14 at 14:40
  • 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);` – jacqbus Mar 17 '23 at 07:59
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;
}
scrblnrd3
  • 7,228
  • 9
  • 33
  • 64