1

I have some template literals as values in a json file. When I access the values I need the values of the variables not the string of the template literal.

I have tried adding back-tick (`) like this but did not work:

value = '`' + value + '`';

Here is a snip of the code I'm trying to run:

const map = require('./mapping.json');

// declared here for testing
const engagement_id = '000909000132';
const start_date = '08/08/2011';

let obj = {};
for (let header in map) {
    value = map[header].value;

    // Do other things

    obj[header] = value;
}

my mapping.json looks something like this:

{
    "C_ID": {
    "value": "16520780,${engagement_id}"
    },
    "C_DATE": {
    "value": "${start_date}",
    "format": "mm/dd/yy",    
    },
    "SURV_TYPE": {
    "value": "S"
    }
}

console.log(obj) gives me this:

{ C_ID: '16520780,${engagement_id}',
  C_DATE: '${start_date}',
  SURV_TYPE: 'S' }

But what I want is the object to have the actual values of the variables like this:

{ C_ID: '16520780,000909000132',
  C_DATE: '08/08/2011',
  SURV_TYPE: 'S' }
mitapia
  • 13
  • 2

2 Answers2

0

Template literals are part of JavaScript source code.

You can't put JavaScript source code in a string and then just use it: It is data, not code.

You could, possibly, use eval(), but that brings its own share of problems and security risks.

Use a template library instead. For example, Nunjucks.

const map = {
  "C_ID": {
    "value": "16520780,{{engagement_id}}"
  },
  "C_DATE": {
    "value": "{{start_date}}",
    "format": "mm/dd/yy",
  },
  "SURV_TYPE": {
    "value": "S"
  }
};

const engagement_id = '000909000132';
const start_date = '08/08/2011';

let obj = {};
for (let header in map) {
  const value = nunjucks.renderString(map[header].value, {
    engagement_id,
    start_date
  })
  obj[header] = value;
}

console.log(obj);
<script src="https://cdnjs.cloudflare.com/ajax/libs/nunjucks/3.0.1/nunjucks.min.js"></script>
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

You could use String.replace() with a function to return the corresponding value:

const map = {
    "C_ID": {
    "value": "16520780,${engagement_id}"
    },
    "C_DATE": {
    "value": "${start_date}",
    "format": "mm/dd/yy",    
    },
    "SURV_TYPE": {
    "value": "S"
    }
};

const values = {
  engagement_id: '000909000132',
  start_date: '08/08/2011',
};

const replacer = (_, p1) => (values[p1]);

let obj = {};
for (let header in map) {
    value = map[header].value.replace(/\${(.+)}/, replacer);

    // Do other things

    obj[header] = value;
}

console.log(obj);
Fraction
  • 11,668
  • 5
  • 28
  • 48