2016-08-29 4 views
0

환경 변수를 자바 스크립트에서 값을 설정하는 객체로 변환하려고 시도하고 있지만이를 수행하는 가장 좋은 방법을 모르겠습니다. 내가 지금까지 무엇을 가지고JS에서 환경 변수를 객체로 변환하는 방법은 무엇입니까?

{ 
    sample: { 
     env: { 
      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 
} 

답변

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); 

단순히 넣으려면 :

  • 우리거야 모든 환경 변수 (from process.env)
  • 분할 밑줄 키 이름을 반복 그리고 다시, 각각의 루프 키 (['HELLO', 'WORLD', 'HI'])
  • 객체에 할당 ({ hello: {} } ->{ hello: { world: {} } } ->{ hello: world: { hi: ? } } })
  • 우리가 더 이상 키가 남아있는 경우 실제 값 ({ hello: { world: { hi: 5 } } })
0

충분히 재미있게, 난 그냥 완료 코드입니다. 나를 위해 노력하고 내가 사용하여 종료하는 것은 적합하지 않지만 :

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); 
} 

(타이프 라이터 형 주석)

여기 아이디어는, 각각의 키를 분할 내리막 길의 대상 객체를 생성하는 것입니다

, 그런 다음 최종 값을 설정하십시오.

0

이다 그것에 내 빠른 걸릴 :

var object = {}; // the object to store the value in 
var name = "SAMPLE_ENV_VAR"; // the environment variable key 
var value = "value"; // the value of the environment variable 

// helper function to automatically create an inner object if none exists 
function getOrCreateInnerObj(obj, name) { 
    if (!obj.hasOwnProperty()) { 
    obj[name] = {}; 
    } 
    return obj[name]; 
} 

// an array of the individual parts (e.g. ["sample", "env", "var"]) 
var keyParts = name.toLowerCase().split("_"); 

// innerObj will contain the second to last element object in the tree based on the array of keys 
var innerObj = getOrCreateInnerObj(object, keyParts[0]); 
for (var i = 1; i < keyParts.length - 1; i++) { 
    innerObj = getOrCreateInnerObj(innerObj, keyParts[i]); 
} 

// set the value itself 
innerObj[keyParts[keyParts.length - 1]] = value; 

$("body").html(JSON.stringify(object)); 

핵심 부품의 배열의 마지막 요소를 제외한 모든이, 당신이 얻을 또는 현재 부모 개체에서 개체를 생성하기위한 그것의 요점이며, 이 키를 누른 다음 마지막 키를 제외한 나머지 키를 반복하면 두 번째 - 마지막 내부 개체가 생기고 값을 설정할 수 있습니다.

편집 : Working example

편집 2 : Here 같은 일

0
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})); 
에 할당하지
관련 문제