Javascript 如何将环境变量转换为JS中的对象?
我试图将环境变量转换为JavaScript中配置的值对象,但我不知道实现这一点的最佳方法 想法是将Javascript 如何将环境变量转换为JS中的对象?,javascript,node.js,env,Javascript,Node.js,Env,我试图将环境变量转换为JavaScript中配置的值对象,但我不知道实现这一点的最佳方法 想法是将SAMPLE\u ENV\u VAR=value输出为: { sample: { env: { var: value } } } 到目前为止,我所拥有的: const _ = require('lodash'); const process = require('process'); _.each(process.env,
SAMPLE\u ENV\u VAR=value
输出为:
{
sample: {
env: {
var: value
}
}
}
到目前为止,我所拥有的:
const _ = require('lodash');
const process = require('process');
_.each(process.env, (value, key) => {
key = key.toLowerCase().split('_');
// Convert to object here
}
有趣的是,我昨晚刚刚完成了一个个人项目的代码。我最终使用的东西并不理想,但对我有用:
export function keyReducer(
src: any,
out: any,
key: string,
pre: string,
del: string
): ConfigScope {
const path = key.toLowerCase().split(del);
if (path[0] === pre.toLowerCase()) {
path.shift();
}
if (path.length === 1) { // single element path
const [head] = path;
out[head] = src[key];
} else {
const tail = path.pop();
const target = path.reduce((parent: any, next: string) => {
if (parent[next]) {
return parent[next];
} else {
return (parent[next] = <ConfigScope>{});
}
}, out);
target[tail] = src[key];
}
return out;
}
static fromEnv(env: Environment, {prefix = 'ABC', delimiter = '_'} = {}) {
const data: ConfigScope = Object.keys(env).filter(key => {
return StringUtils.startsWith(key, prefix);
}).reduce((out, key) => {
return keyReducer(env, out, key, prefix, '_');
}, <ConfigScope>{});
return new Config(data);
}
导出功能键减速器(
src:任何,
出:有,,
键:字符串,
前:字符串,
德尔:字符串
):ConfigScope{
const path=key.toLowerCase().split(del);
if(路径[0]==pre.toLowerCase()){
path.shift();
}
如果(path.length==1){//单个元素路径
const[head]=路径;
out[head]=src[key];
}否则{
const tail=path.pop();
const target=path.reduce((父级:任意,下一级:字符串)=>{
if(父级[下一个]){
返回父项[下一步];
}否则{
返回(父[下一个]={});
}
},外出);
target[tail]=src[key];
}
返回;
}
静态fromEnv(env:Environment,{prefix='ABC',delimiter='.}={}){
常量数据:ConfigScope=Object.keys(env.filter)(key=>{
返回StringUtils.startsWith(键,前缀);
}).reduce((输出,键)=>{
返回键减速器(env、out、键、前缀“"”);
}, {});
返回新的配置(数据);
}
(带有类型脚本类型注释)
这里的想法是分割每个关键点,在向下的过程中创建目标对象,然后设置最终值 这是我对它的快速理解:
var object={};//要在其中存储值的对象
var name=“SAMPLE\u ENV\u var”;//环境变量键
var value=“value”;//环境变量的值
//帮助器函数,用于自动创建内部对象(如果不存在)
函数getOrCreateInnerObj(obj,名称){
如果(!obj.hasOwnProperty()){
obj[name]={};
}
返回obj[名称];
}
//单个部件的数组(例如,[“样本”、“环境”、“变量”])
var keyParts=name.toLowerCase().split(“”);
//innerObj将根据键数组包含树中倒数第二个元素对象
var innernobj=getorcreateinnernobj(对象,keyParts[0]);
对于(变量i=1;i
其要点是,对于关键部分数组中除最后一个元素外的所有元素,您可以在该关键点的当前父对象中获取或创建一个对象,并且在对除最后一个关键点之外的所有关键点重复此操作后,您将拥有倒数第二个内部对象,然后可以对其设置值
编辑:
编辑2:是一个更清晰的示例,它使用一点递归来完成同样的事情这里有一个基于您的更完整的解决方案:
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);
简而言之:
- 我们将循环遍历每个环境变量(
)来自process.env
- 用下划线拆分键名,然后再次循环每个键(
)['HELLO','WORLD','HI']
- 将其分配给对象(
->{code>{hello:{world:{}}}->{hello:{}
){hello:world:{hi:?}}}
- 当我们不再剩下任何键时,将其分配给实际值(
){hello:{world:{hi:5}}}
。
请描述您的答案、工作原理以及与代码相关的任何其他信息。粘贴修复问题的代码非常有帮助,但解释原因却很有帮助。
const basic = {};
let current;
`YOUR_VARIABLE_NAME`
.split(`_`)
.forEach((item, index, array) => {
if(index === 0) {
return current = basic[item] = {};
}
if(index === array.length - 1) {
return current[item] = process.env.HE_LO_NA;
}
current = current[item] = {};
});
console.log(require('util').inspect(basic, {depth: 10}));
const _ = require('lodash');
const process = require('process');
const result = Object.entries(process.env).reduce((acc, [key, value]) => {
_.set(acc, key.toLowerCase().replace('_', '.'), value);
return acc;
}, {})