首页 > 解决方案 > 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.

标签: javascriptobject

解决方案


您需要检查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])


推荐阅读