Skip to content

Instantly share code, notes, and snippets.

@aelindeman
Created January 20, 2020 18:46
Show Gist options
  • Save aelindeman/0411701a8d9e3289a198c9ec1f60113e to your computer and use it in GitHub Desktop.
Save aelindeman/0411701a8d9e3289a198c9ec1f60113e to your computer and use it in GitHub Desktop.
convert an array of environment variables to a Javascript object

example usage:

const envArray = [
  'PATH=/usr/local/bin:/usr/bin:/usr/sbin',
  'HOME=/home/alex',
  'FOO=bar'
];

const envObject = toEnvObject(envArray);
// {
//   'PATH': '/usr/local/bin:/usr/bin:/usr/sbin',
//   'HOME': '/home/alex',
//   'FOO': 'bar'
// }

const foo = envObject.FOO
// 'bar'
const toEnvObject = arr =>
arr.filter(it => it.length > 0)
.map(it => it.split('=', 2))
.filter(([key]) => key.length > 0)
.reduce((obj, [key, value]) => ({ ...obj, [key]: value }), {});
const toEnvObject = (arr: string[]): { [key: string]: string } =>
arr.filter(it => it.length > 0)
.map(it => it.split('=', 2))
.filter(([key]) => key.length > 0)
.reduce((obj, [key, value]) => ({ ...obj, [key]: value }), {});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment