0

I have a somewhat strange question, I would like to know if it is possible to use a string as an entire reference to get a value from an object within an array.

This is my array:

const myArray = [
    {name: 'element1', id: 'elementid1'},
    {name: 'element2', id: 'elementid2'}
];

where myArray[0]["name"] returns: 'element1'

Would it be possible to have this entire reference: myArray[0]["name"] as a string: 'myArray[0]["name"]' and use it to reference to this value.

So this: getViaString returns 'element1' with the following set up:

const getViaString = 'myArray[0]["name"]';

I have set up this fiddle as it probably explains better what I am trying to do: jsfiddle

Thanks.

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
prettyInPink
  • 3,291
  • 3
  • 21
  • 32

2 Answers2

1

yes you can do it with

const getViaString = eval('myArray[0]["name"]');
Aziz.G
  • 3,599
  • 2
  • 17
  • 35
1

You could potentially use eval() - not recommended.

const getViaString = eval("myArray[0]['name']");
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79