Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ways to interpolate template variables inside JavaScript objects

I'd like to do the following

var obj = {
  animal: "${animal}"
};

var res = magic(obj, {animal: "cat"});

// res => {animal: "cat"}

magic is some function that does the dirty work. Obviously obj could be more complex with multiple keys, nested arrays and so on. The template variable could be inside an array like this

var obj = {
  animals: ["cat", "dog", "${animal}", "cow"]
};

and it could be anywhere in the array so simply doing obj.animals[2] = "bat"; isn't feasible.

I've found the underscore-tpl library with which I can achieve what I want, but I would like to know if there are other solutions for future reference and because I had a hard time finding underscore-tpl in the first place.

My actual use is case is that I have a config.json file where I have several declarations like the following

{
  "task1": {
    "command": "command-line-program",
    "args": [
      "--input", "{{input}}",
      "--flag1",
      "--output", "{{output}}",
      "--flag2",
    ],
    "options": {
      "cwd": "path-to-working-dir"
    }
  }
}

I parse this consig.json using JSON.parse(...) and I call require("child_process").spawn with the command, args and options parameters declared in the file, however args change a lot, flags added, reordered and stuff, so simply doing config.task1.args[1] = "<input value>"; involves changing the code that invokes spawn and this is as error prone as it gets.

Update

Based on the accepted answer I've created a simple package (located here) which I can include in my projects, feel free to use it.

like image 696
Kohányi Róbert Avatar asked Jul 30 '15 16:07

Kohányi Róbert


1 Answers

You could JSON.stringify the object, then replace your search value with the actual value, then JSON.parse the result:

function magic(o, a) {
    var j = JSON.stringify(o);
    for (var k in a) {
            j = j.split('${'+k+'}').join(a[k]);
    }
    return JSON.parse(j);
}
like image 126
dave Avatar answered Oct 18 '22 10:10

dave