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
  • 40,575
  • 10
  • 44
  • 74
prettyInPink
  • 3,002
  • 3
  • 16
  • 29

2 Answers2

1

yes you can do it with

const getViaString = eval('myArray[0]["name"]');
G.aziz
  • 3,365
  • 1
  • 13
  • 30
1

You could potentially use eval() - not recommended.

const getViaString = eval("myArray[0]['name']");
Jack Bashford
  • 40,575
  • 10
  • 44
  • 74