javascript - How to read environment variable key and value dynamically in NodeJS - Stack Overflow

I would like to read all the environment variables key and value dynamically and form the array like be

I would like to read all the environment variables key and value dynamically and form the array like below:

environment: [
    {
        name: 'DB_NAME',
        value: 'myDatabase'
    },
    {
        name: 'DB_USER_NAME',
        value: 'admin'
    },
    {
        name: 'DB_PASSWORD',
        value: 'admin'
    },
    {
        name: 'DB_TABLE_NAME',
        value: 'myTable'
    },
]

I'm able to print all the environment variables but I'm struggling to get the key and value and form the array dynamically - could someone please help me with this? Appreciate your help in advance. Thanks.

const env = require('dotenv').config();
var environmetList = process.env
console.log("printing env variables", environmetList)
const environment = [];

I would like to read all the environment variables key and value dynamically and form the array like below:

environment: [
    {
        name: 'DB_NAME',
        value: 'myDatabase'
    },
    {
        name: 'DB_USER_NAME',
        value: 'admin'
    },
    {
        name: 'DB_PASSWORD',
        value: 'admin'
    },
    {
        name: 'DB_TABLE_NAME',
        value: 'myTable'
    },
]

I'm able to print all the environment variables but I'm struggling to get the key and value and form the array dynamically - could someone please help me with this? Appreciate your help in advance. Thanks.

const env = require('dotenv').config();
var environmetList = process.env
console.log("printing env variables", environmetList)
const environment = [];
Share Improve this question asked Nov 14, 2021 at 21:36 Mike MarshMike Marsh 3955 silver badges16 bronze badges 1
  • What is process.env and what happened to env? Is process.env an object containing the system environment variables or an array of objects with settings? – jabaa Commented Nov 14, 2021 at 21:45
Add a ment  | 

1 Answer 1

Reset to default 7

Using Object#entries, get the list of pairs in process.env. Then, iterate over it using Array#map to get a list of objects with name and value:

Object.entries(process.env).map(([key, value]) => ({ name: key, value }))

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745295018a4621087.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信