How to make extended String patterns in Javascript with loops and control instructions

Basically at runtime I get an array like the following

var colors = ['red', 'green', 'blue'];

and I need to build a JSON string as below

{
    "color" : {
        "name" : "foo",
        "properties" : {
            ...
        }
    },
    "green" : {
        "name" : "foo",
        "properties" : {
            ...
        }
    },
    "blue" : {
        "name" : "foo",
        "properties" : {
            ...
        }
    }
}

Is there any structure of String patterns that supports loops and control instructions for constructing a JSON string, as described above.

+6
source share
3 answers

You can try using the Nunjucks package. It supports both javascript and npm libraries. A template can be declared as follows (name it colors.template):

{
    {% for color in colors %}
    "{{ color }}"  : {
      hashCode : "#CCC"
     }
    {% else %}
    {% endfor %}
}

And you can parse the json template as follows:

var nunjucks = require('nunjucks');
nunjucks.configure({ autoescape: true });
var output = nunjucks.render('colors.template', {colors : ['red', 'green', 'blue'] });
+7
source

Fit.UIs templating engine :

http://fitui.org/Core-Template.html

HTML , HTML - :

var t = new Fit.Template(true);

// Load embedded HTML
tpl.LoadHtml(`
    <h1>{[MyHeadline]}</h1><br>
    <p>{[Description]}</p>
    <ul>
        <!-- LIST MyItems -->
            <li>{[ItemTitle]}</li>
        <!-- /LIST MyItems -->
    </ul>
`);
// Load HTML from external HTML file
t.LoadUrl("view.html", function(sender)
{
    // Template is ready to be populated
    t.Content.MyHeadline = "Welcome";
    t.Content.Description = "This is a test..";

    for (var i = 1 ; i <= 5 ; i++)
    {
        var item = t.Content.MyItems.AddItem();
        item.ItemTitle = "Item " + i;
    }

    t.Update();
});

t.Render(document.body);

, JSON , Fit.Template.

NPM, intellisense:

https://www.npmjs.com/package/fit-ui

+3

With simple javascript:

function arrayToJSONProp(array, json) {
  var strJson = JSON.stringify(json);
  var output = "{";
  for(var i = 0; i < array.length; i++) {
    var elem = array[i];
    output += '"' +elem +'" : ' +strJson +", ";
  }
  return JSON.parse(output.slice(0, -2) +"}");
}

var colors = ["red", "green", "blue"]; // Colors array
var prop = { // JSON obj input
  "name" : "foo",
  "properties" : {
    "ran": "test"
  }
}

console.log(arrayToJSONProp(colors, prop)); // Output of JSON obj

http://jsfiddle.net/t6wka5x9/3/

+1
source

All Articles