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)

0

1 Answer 1

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" 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.