Mastering advanced String templating using loops and control statements in Javascript

During runtime, I receive an array similar to the example below:

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

I then need to create a JSON String that looks like this:

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

Are there any String templating frameworks available that support loops and control statements for constructing a JSON String in the specified format?

Answer №1

Fit.UIs has a user-friendly templating engine:

You have the option to load HTML content either directly embedded or from an external HTML file. For example:

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);

Of course, you will need to populate your JSON object manually, but this can be easily done on top of Fit.Template.

If you prefer using NPM packages with Typings support for intellisense, check out the package available here:

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

Answer №2

If you're looking for a versatile solution, consider giving the Nunjucks package a try. It offers support for both JavaScript and npm libraries. Declare your template named 'colors.template' like this:

{
    {% for hue in colors %}
    "{{ hue }}"  : {
      hexCode : "#CCC"
     }
    {% else %}
    {% endfor %}
}

To parse the JSON template, use the following code snippet:

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

Answer №3

Using vanilla JavaScript:

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

var fruits = ["apple", "banana", "orange"]; // Fruits array
var details = { // Input JSON object
  "name" : "bar",
  "info" : {
    "size": "large"
  }
}

console.log(convertArrayToJSON(fruits, details)); // Resulting JSON object

http://jsfiddle.net/abcd1234/5/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Oops! There was an error: Unable to find a solution for all the parameters needed by CountdownComponent: (?)

I'm currently working on creating a simple countdown component for my app but I keep encountering an error when I try to run it using ng serve. I would really appreciate some assistance as I am stuck. app.module.ts import { BrowserModule } from &apo ...

External CSS File causing improper sizing of canvas image

I have been working on implementing the HTML5 canvas element. To draw an image into the canvas, I am using the following javascript code: var img = new Image(); var canvas = this.e; var ctx = canvas.getContext('2d'); img.src = options.imageSrc; ...

Manipulating a textarea in jQuery by inserting a string and selecting a specific portion of it

Just as seen on SO with the B button: **bold text** Including that bold text is automatically highlighted and the cursor is placed right before the b ...

The destination path specified in npm copyfiles is not accurate

Currently, I am utilizing the npm package known as "copyfiles" within my buildscript. However, I have noticed that the target directory does not match the expected output. "copy-template": "copyfiles \"./src/**/*.html\" \"dist\"", The ...

The button fails to log any text to the developer console

Attempting to verify the functionality of my button by logging a message on the developer console. However, upon clicking the button, the text does not appear in the console. import { Component, EventEmitter, Input, Output } from '@angular/core'; ...

What is the best way to address background-image overflow on a webpage?

I'm facing a challenge in removing the overflow from a background-image within a div. There are 4 divs with similar images that combine to form one background image (I adjust the position of each image so they align across the 4 divs). Essentially, I ...

Efficiently managing routes by segmenting them into distinct files

My Express app is structured in the standard Express 4 format, with dependencies at the top, followed by app configuration, routes, and finally the listen function. I'm currently working on organizing my routes into categorized files (e.g., routes/au ...

What makes componentDidMount the ideal location to initiate AJAX requests?

It is quite common to see AJAX requests being fired at the componentDidMount hook in many React projects. However, I find it hard to understand this suggested practice. For example, consider a component where the AJAX request depends on a prop from the pa ...

Updating a database with a loop of React Material UI toggle switches

I am trying to implement a material UI switch feature that can update the Active and De-Active status of users in the database directly from the Admin Panel. Currently, the database updates are functioning correctly when toggling the switches. However, th ...

Ways to ensure that the form data stays consistent and visible to the user continuously

Is there a way to ensure that the user submits the form, stores it in a MYSQL database, and then displays the same submitted data in the form field? <div class="form-group"> <label class="control-label col-sm-2" for="lname">Last Name*</l ...

A Guide to Adding an NPM Package to a Lerna and Yarn Workspaces Repository

Is it necessary to navigate into the specific directory and use yarn add <package> to add a dependency to a package? Or is there a command that can be run in the root directory, possibly with a flag such as --workspace=<workspace-name>? ...

The JSON.stringify() function helps to convert data into a JSON-formatted string, avoiding any potential "c

connection.query( 'SELECT DeskName FROM desks WHERE stat = ?',["Booked"], function(err, rows){ if(err) { throw err; }else{ try{ var dataToParse = new Array(); dataToParse = rows; res.render('workspaces.html',{parsedArray : JS ...

Developing a React application is encountering issues with displaying messages that suggest difficulties in resolving the dependency tree and addressing conflicts within the upstream dependencies

Every time I try to create a React app using Create React App in the terminal, I encounter this frustrating error. Installing template dependencies using npm... npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! W ...

Is it advisable to implement the modular pattern when creating a Node.js module?

These days, it's quite common to utilize the modular pattern when coding in JavaScript for web development. However, I've noticed that nodejs modules distributed on npm often do not follow this approach. Is there a specific reason why nodejs diff ...

Encountering TS2304 error messages such as "Cannot find name 'File'" or "Cannot find name 'ReadableStream'" while executing the "npm run tsc" command

My Node.js application utilizes the "watson-developer-cloud" module, which was added using the command "npm install --save watson-developer-cloud". Upon running "npm run tsc", I encountered the following error: node_modules/ibm-cloud-sdk-core/lib/content ...

Fetching Information From Database Using PHP

I am encountering an issue while attempting to transfer data from my HTML table to my modal (without using bootstrap). In the image below, you can see that I have successfully displayed data from MySQL database in the table. The problem arises when I clic ...

Is there a tool available that enables the utilization of local NPM dependencies within the PATH environment variable?

Are there any NPM packages or tools available that have the capability to automatically add local NPM packages to the $PATH? This feature could enable the creation of a local development environment that is completely isolated from other projects. While ...

Choosing an element from an array in JavaScript that meets a certain criteria

How can I isolate an object from an array where the value for the "slug" key is "A"? For instance, consider the following data: var allItems = [ { "slug": "henk", "company_founded": "2008", "company_category": "Clean", ...

error: unrecognized command (npm)

I'm currently in the process of setting up a connector for Elm-d3 that I came across on Github. Elm is a functional-reactive programming language created by Evan Czaplicki d3.js is a popular graphics meta-library developed by Michael Bostock El ...

Uninstall all packages that are no longer listed in the package.json file using Npm

Seeking guidance on how to uninstall packages from the node_modules directory that are no longer listed in package.json. These packages were removed by another developer and the package.json file has been updated on git. Any tips on how to accomplish this ...