-1

const ob = {user: {name: 'Jane', extension: '1234'}};
const param = 'name';
const path = `ob.user.${param}`;
console.log(path);

So this prints "ob.user.name". What I want is for it to print "Jane". I can do that if I call eval() on path, but I'm told that eval() is slow, insecure, and possibly carcinogenic.

How can I interpolate a value into path and get to the value to which path refers without using eval()?

(The code in question will be going inside a React component, which I think precludes any solutions the window object.)

Tony Abrams
  • 4,505
  • 3
  • 25
  • 32
anaximander
  • 167
  • 1
  • 2
  • 12
  • 1
    would `ob.user[param]` do the trick ? – kigiri Jun 25 '19 at 16:11
  • 1
    *"...I'm told that `eval()` is slow, insecure, and possibly carcinogenic."* **LOL** – T.J. Crowder Jun 25 '19 at 16:14
  • Using [Alnitak's solution](https://stackoverflow.com/a/6491621/157247) to the linked question: https://jsfiddle.net/tjcrowder/mgpxzws9/ – T.J. Crowder Jun 25 '19 at 16:17
  • How's this for an approach? https://jsfiddle.net/tj4ke8hg/ @T.J.Crowder – weegee Jun 25 '19 at 16:26
  • @weegee - If you don't need a **string** path, don't use one. More: http://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable I assumed you needed to use a string *path*, not just a string *name*. – T.J. Crowder Jun 25 '19 at 16:34

1 Answers1

0

You can access object properties using "array notation" too:

const ob = {user: {name: 'Jane', extension: '1234'}};
const param = 'name';
const path = ob.user[param];
console.log(path); // Outputs "Jane"
Stuart
  • 6,630
  • 2
  • 24
  • 40