limit
limit

Reputation: 647

How to use Template literals (Template strings) used to return object var

I have a set of constants I am trying to make a simple env helper method to return those constants like below. I see you can use Template literals (Template strings) to parse variables, but I cannot get this to work.

Is this possible or is there a better way to do this?

export default {

    env(constant: any) {
        return `${TEST_VARS}.${constant}`;
    }
}

export const TEST_VARS = {
    DB_CONFIG: {
        db_name: 'test.db',
        db_location: '_default'
    }
}

// how do I return test.db from this is that possible?

console.log(default.env('DB_CONFIG.db_name'));  // test.db.  

Upvotes: 0

Views: 66

Answers (2)

Zachary Haber
Zachary Haber

Reputation: 11017

Edit: I entirely missed a crucial piece of how you are working with it:

I'd recommend using lodash's get function https://lodash.com/docs/4.17.15#get as it's super convenient and does pretty much exactly what you want.

 export default {

    env(constant: any) {
        return _.get(TEST_VARS,constant);
    }
}

Old answer:

Try this. Computed property access is great and will greatly simplify property accessing with a variable. There are more details here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors

 export default {

    env(constant: any) {
        return TEST_VARS[constant];
    }
}

Upvotes: 1

Code Maniac
Code Maniac

Reputation: 37757

You can build an accessor function and call it inside template literal

const keyUnifier = key => key.replace(/(\w+)\[(\d+)\]/g, "$1" + ".$2")
  .replace(/\[([^\]]+)\]/g, ".$1")
  .split('.')

function accessor(key) {
  let temp = TEST_VARS
  let keyArr = keyUnifier(key)
  while (keyArr.length) {
    if (typeof temp === 'object') {
      temp = temp[keyArr[0]]
      keyArr.shift()
    } else {
      temp = 'Not found'
      keyArr = []
    }
  }
  return temp
}

function env(keyPath) {
  return `${accessor(keyPath)}`;
}
const TEST_VARS = {
  DB_CONFIG: {
    db_name: 'test.db',
    db_location: '_default',
    db_arr: [
      "db_key",
      {
        deep: "Key"
      }
    ]
  }
}

console.log(env('DB_CONFIG.db_name'));
console.log(env('DB_CONFIG.db_name.newKey'));
console.log(env('DB_CONFIG.db_arr[1].deep'));
console.log(env('DB_CONFIG.db_arr[1][deep]'));

Upvotes: 1

Related Questions