Node.js configuration object based on environment variables
Ideally, I would suggest two changes the the overall design:


the environment variable names could have one consistent prefix, e.g. MONGO_ and ATLAS_
the keys of the config object could match the environment variable names, e.g. databaseName would match MONGO_DATABASE_NAME


If that for some reason is not possible, then we can hardcode the config-to-environment name mapping:

function getConfigurationFor(prefix) {
  const configMap = {
    username:     'HUB_USERNAME',
    password:     'HUB_PASSWORD',
    cluster:      'CLUSTER',
    hosts:        'HOSTS',
    databaseName: 'DATABASE',
    replicaSet:   'REPLICA_SET'
  }

  prefix = prefix.toUpperCase() + '_'
  return Object
    .entries(configMap)
    .reduce((result, [key, envKey]) =&gt; {
      result[key] = process.env[prefix + envKey]
      return result
    }, {})
}

const config = getConfigurationFor(
  process.env.NODE_ENV === 'production'
    ? 'atlas'
    : 'mongo'
)




if you can make these design changes, then we have more flexibility: we can create a function that would read all the environment variables that start with a certain prefix and return this as a plain JavaScript object:

const getEnvironmentForPrefix(prefix, source) {
  const camelCase = require('lodash.camelcase')

  return Object
    .entries(source || process.env)
    .filter([key] =&gt; key.startsWith(prefix))
    .map(([key, value]) =&gt; [key.substring(prefix.length), value])
    .map(([key, value]) =&gt; [camelcase(key), value])
    .reduce((result, [key, value]) =&gt; {
      result[key] = value
      return result
    }, {})    
}

const config = getEnvironmentForPrefix(
  process.env.NODE_ENV === 'production'
    ? 'ATLAS_'
    : 'MONGO_'
)