javascriptnode.jsenv

How do I convert an environment variable to an object in JS?


I'm trying to convert an environment variable into an object of values for configuration in JavaScript but I don't know the best way to achieve this.

The idea would be to output SAMPLE_ENV_VAR=value as:

{
    sample: {
        env: {
            var: value
        }
    }
}

What I have so far:

const _ = require('lodash');
const process = require('process');

_.each(process.env, (value, key) => {
    key = key.toLowerCase().split('_');
    // Convert to object here
}

Solution

  • Here's a more complete solution based on yours:

    const _ = require('lodash');
    const result = {};
    
    // We'll take the following as an example:
    // process.env = { HELLO_WORLD_HI: 5 }
    // We'll expect the following output:
    // result = { hello: { world: { hi: 5 } } }
    _.each(process.env, (value, key) => {
        // We'll separate each key every underscore.
        // In simple terms, this will turn:
        // "HELLLO_WORLD_HI" -> ['HELLO', 'WORLD', 'HI']
        const keys = key.toLowerCase().split('_');
    
        // We'll start on the top-level object
        let current = result;
    
        // We'll assign here the current "key" we're iterating on
        // It will have the values:
        // 'hello' (1st loop), 'world' (2nd), and 'hi' (last)
        let currentKey;
    
        // We'll iterate on every key. Moreover, we'll
        // remove every key (starting from the first one: 'HELLO')
        // and assign the removed key as our "currentKey".
        // currentKey = 'hello', keys = ['world', 'hi']
        // currentKey = 'world', keys = ['hi'], and so on..
        while ( (currentKey = keys.shift()) ) {
            // If we still have any keys to nest,
            if ( keys.length ) {
              // We'll assign that object property with an object value
              // result =// { HELLO: {} }
              current[currentKey] = {};
    
              // And then move inside that object so
              // could nest for the next loop
              // 1st loop: { HELLO: { /*We're here*/ } }
              // 2nd loop: { HELLO: { WORLD: { /*We're here*/ } } }
              // 3rd loop: { HELLO: { WORLD: { HI : { /*We're here*/ } } } }
              current = current[currentKey];
            } else {
              // Lastly, when we no longer have any key to nest
              // e.g., we're past the third loop in our example
              current[currentKey] = process.env[key]
            }
        }
    });
    
    console.log(result);
    

    To simply put: