Please take a look at the following code:
const config = {
prefix: 'MYAPP',
MYAPP_HOST: '1',
MYAPP_HOST: '2',
[ this.prefix + '_HOST' ]: 'localhost',
}
console.log(`${config.MYAPP_HOST}`)
console.log(`${config.${config.prefix}_HOST}`)
What's the proper way to make both outputs to print localhost
?
I know one way to make
[ this.prefix + '_HOST' ]: 'localhost',
working is to define this.prefix
as an function, so it becomes:
[ this_prefix() + '_HOST' ]: 'localhost',
However, I'm hoping that, because the prefix
belongs to const config
, so that it could be defined within const config
, not outside of it.
As for ${config.prefix}_HOST
, I'm just trying to construct the string MYAPP_HOST
, but nested with template literal. Is there any way to make it possible?
EDIT:
Nested template makes no sense
while it might not be obvious why I need to do this, because the question has been simplified to focus on the technique, here is the a less simplified version of what I want. take a look at the following code:
const config = {
prefix: 'MYAPP',
app: { port: 3000 },
db: { host: 'localhost', port: 27017, name: 'db' },
url: function () { return `driver:/${process.env.MYAPP_HOST || this.db.host}:${process.env.MYAPP_PORT || this.db.port}/${process.env.MYAPP_NAME || this.db.name}` },
}
and I don't want to use string literal MYAPP
in the process.env.MYAPP_...
but want to use the prefix
variable instead. Makes sense or not aside, this is what I need to do. Now how to do that?
UPDATE:
The answers to the above question has been spreading at many places, so here is the concise summary of the solution (to OP):
const prefix = 'MYAPP'
const config = {
prefix,
MYAPP_HOST: '1',
MYAPP_HOST: '2',
[ prefix + '_HOST' ]: 'localhost',
}
console.log(`${config.MYAPP_HOST}`)
console.log(`${config[config.prefix+'_HOST']}`)
Thanks everyone, upvoting to your all!