Search code examples
javascriptreactjsecmascript-6ecmascript-2016

Can you use template strings as an object value?


Is there a way to create a hash of template strings?

Something like:

const myStrings = {
   a: `myStringA${test}`,
   b: `myStringB${test}`
}

And then somewhere else, you can do something like: getString(index, test), and it can index into the object. I know that the above is wrong, but just wanted to give an example of what I have in mind. For instance, getString(a, "Cat") would return: myStringACat


Solution

  • For your use case I would see the following:

    var myStrings = {
        a: "myStringA${test}",
        b: "Name: ${name}, Id: ${id}",
    	
        getString: function(index, o) {
          var string = this[index];
    
          Object.keys(o).forEach(function(key) {
            if (string.indexOf("${" + key + "}")) {
    	      string = string.replace("${" + key + "}", o[key]);
            }
          });
    
          return string;
        },
    };
    
    console.log(
      myStrings.getString("a", {test: "Cat"}),
      " ",
      myStrings.getString("b", {name: "Arber", id: 123})
    );
    
    // "myStringACat"
    // "Name: Arber, Id: 123"