0

I am having the object config and when I fetch the config["RegionId"], it will give me ${Region}. Now I want to fetch the value of Region. As I have got ${Region}, I thought I could do console.log(`${val}`) to get 'abc'. But it is not working.

How to get this? This is what I have tried,

var config = {
    "RegionId" : "${Region}"
}

var Region = 'abc'
var val = config['RegionId']

console.log(`${val}`)
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
Abinash Biswal
  • 137
  • 1
  • 1
  • 9

2 Answers2

3

Don't put double quotes around the property value. Use back-ticks (for template literal strings) as you are doing for val. And make sure you've declared Region prior to attempting to access it.

var Region = 'abc';

var config = {
    "RegionId" : `${Region}`
};

var val = config['RegionId'];
console.log(`${val}`);

And while your question is centered around template literals, I hope you know that for this scenario, they add no value and are overkill. Here's the same thing with regular strings variables:

var Region = 'abc';

var config = {
    "RegionId" : Region
};

console.log(config['RegionId']);
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
-1

try using eval function

var config = {
    "RegionId" : "${Region}"
}

var Region = 'abc'
var val = config['RegionId']


console.log(eval("`"+val+"`"));
Rohit
  • 75
  • 1
  • 5
  • 2
    `eval()` is evil and there are really only VERY VERY RARE use cases when it is needed. Most situations that use `eval()` wind up needing it because the solution was not thought out properly. – Scott Marcus Jul 15 '20 at 15:17
  • This is working. But is there any standard javascript way to do that? I am asking just for knowledge. And how safe is eval? – Abinash Biswal Jul 15 '20 at 15:35
  • @AbinashBiswal `eval()` is not safe, changes scope, and as my comment above says, should really never be used. This is why `JSON.parse()` was created. It's a safer version of `eval()` for JSON strings, but as I say in my above comment. JSON strings should never contain code, which is what you are doing. You should re-work your thoughts about what you are doing. – Scott Marcus Jul 15 '20 at 15:41