javascript - How can I get item from javascript object using keys?
问题描述
I have a javascript file defined in a class inside an express app.
import dotenv from 'dotenv';
dotenv.config();
class Settings {
static getSettings() {
const activeEnvironment = process.env.NODE_ENV;
console.log('active ', activeEnvironment)
const settings = {
development: {
databaseName: 'foods',
},
production: {
databaseName: 'foods',
},
test: {
databaseName: 'testdb'
}
};
settings[activeEnvironment] // returns undefined
return settings[activeEnvironment];
}
}
export default Settings;
But the problem I have is that settings[activeEnvironment]
returns undefined
. I have correctly exported NODE_ENV
in my start script set NODE_ENV=production & node --require @babel/register ./bin/www
Anyone can point me on what I'm doing wrong. I'm a bit new to javascript.
Thank you.
解决方案
您需要检查const activeEnvironment = process.env.NODE_ENV;
具有 3 个值之一的值
development, production, test
。
如果不在此列表中的值settings[activeEnvironment]
将返回未定义。
const activeEnvironment = 'test';
console.log('active ', activeEnvironment)
const settings = {
development: {
databaseName: 'foods',
},
production: {
databaseName: 'foods',
},
test: {
databaseName: 'testdb'
}
};
console.log(settings[activeEnvironment])
推荐阅读
- html - Magento 2将背景图像放入正文
- asp.net - 使用 Web API 重定向到 Angular html 页面
- c# - 访问实体框架自动生成的 FK 列
- android - qrcode !barcodeDetector.isOperational() 移动视觉 API
- c++ - 分离线程然后让它超出范围(并让它仍在运行)是否安全?
- networking - 磁盘映射和磁盘挂载有什么区别?什么时候应用这些方法?
- matlab - 使用 matlab 从给定的二进制矩阵创建邻域图
- amazon-web-services - 从 OS 磁盘 EBS 卷手动创建 AMI 所需的更改
- visual-studio-2015 - 从 txt 文件添加多个包含目录
- javascript - Angular E2E 测试让隐藏元素仅在 E2E 期间显示