0

Consider I've an object myObj And I've a string representing the path to some property inside it: foo.bar

What is the best way to get it from my object?

If I knew the string ahead I would do myObj.foo && myObj.foo.bar to get it safely

A simple solution would be to split the string 'foo.bar'.split('.') and than loop over it.

But i'm sure there is a better way


It's a duplicate of other question. they provided a great solution:

given a path and an obj get the property value this way

path.split('.').reduce((o, i) => o[i], obj)

YardenST
  • 5,119
  • 2
  • 33
  • 54

1 Answers1

0

A simple solution would be to split the string 'foo.bar'.split('.') and than loop over it.

Yep, that sounds like the best way. You can create a helper method that does exactly this, but there's nothing built in to the language or standard libraries to make things simpler than this.

function getFromPath(obj, path) {
 var current = obj;
 for(let piece of path.split('.')) {
  current = current[piece];
 }
 return current;
}

Usage:

getFromPath({foo: {bar: "hello"}}, "foo.bar"); // "hello"
StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315