3

I have this path in a string: var path = 'bonds.international.emergent' and the object portfolio.

I want to access portfolio.bonds.international.emergent, using the path in the path variable.

Something like portfolio[path], which obviously doesn't work. Anyone knows how to do this?

0

1 Answer 1

5

If it's only dots, you can split:

var path = 'bonds.international.emergent';
var target = portfolio;
path = path.split('.');
for(var i = 0; i < path.length; i++) {
  target = target[path[i]];
}
alert(target); // = portfolio.bonds.international.emergent

Else, you can eval:

var target = eval('portfolio.' + path);

But avoid eval if you can.

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.