What is the method to retrieve a javascript object from within a string template?

I am trying to find a way to map data from an object into a string template using JavaScript. Here is an example of the string and object I am working with:


const menu = {
   breakfast: {
      description:'something' 
      }
   meal: {
      description: 'anotherSomething'
      }
}

const template = `<div>
   <ul>
     <li>
       %breakfast.description%
     </li>
     <li>
       %meal.description%
     </li>
   </ul>  
</div>
`

Instead of creating arrays and looping through keys, I am looking for a more elegant solution where I can dynamically access the object directly within the string like in a template literal. Any suggestions or solutions would be greatly appreciated!

Answer №1

Utilize a regular expression replacement with a callback function as the replacement, allowing it to retrieve the value from the object.

const menu = {
  breakfast: {
    description: 'something'
  },
  meal: {
    description: 'anotherSomething'
  }
}

const template = `<div>
   <ul>
     <li>
       %breakfast.description%
     </li>
     <li>
       %meal.description%
     </li>
   </ul>  
</div>
`

let result = template.replace(/%([^%]+)%/g, (g0, g1) => lookup(g1, menu));

console.log(result);

function lookup(path, obj) {
  return path.split('.').reduce((p, c) => p && p[c] || null, obj);
}

The lookup() method referenced in this code snippet was sourced from this answer.

Answer №2

After much exploration, I stumbled upon a clever workaround that involves replacing template variables with embedded template literals which are then evaluated as JavaScript code within the entire template string. One crucial step is to destructure the myMenuInformation object so that the eval function can access those values; otherwise, it may lead to errors or undefined outcomes. This insightful Stack Overflow post and the comprehensive MDN Web Docs on the Eval Function greatly aided me in this process:

Can ES6 template literals be substituted at runtime (or reused)?

MDN Web Docs Eval Function

function swapVariables(myTemplate, myMenuInformation){
   const matches = myTemplate.match(/(?<=\%)(.*?)(?=\%)/g);
    
        if (!matches) {
          return myTemplate;
        }
        const originalTexts = matches.map((m) => ({
          replacementRegex: new RegExp('\\%' + m + '%', 'g'),
          literalVar: '${'+m+'}',
        }));
        
        let newContent = myTemplate;
        originalTexts.forEach((match) => {
          newContent = newContent.replace(
            match.replacementRegex,
            match.literalVar,
          );
        });

        newContent = '`' + newContent + '`'
        var {breakfast, meal} = myMenuInformation
        return eval(newContent)
}

const updatedTemplate = swapVariables(template, menu)
console.log(updatedTemplate)

// OUTPUT:
//<div>
//   <ul>
//     <li>
//     something
//     </li>
//     <li>
//       anotherSomething
//     </li>
//   </ul>  
//</div>

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

Tips for accessing the value of a dynamically created textbox using JavaScript

Hello everyone, I have a couple of questions that I need help with. I am currently working on developing a social networking website similar to Facebook. On this platform, there are multiple posts fetched from a database. However, I am facing an issue w ...

Updating the scope in Angular when changing the image source using ng-src is not working

A snippet inside my controller looks like this: $scope.onFileSelect = function($files) { for(var i = 0; i < $files.length; i++) { var file = $files[i]; $scope.upload = $upload.upload({ url: '/smart2/api/files/profi ...

Make a call to a URL in Symfony2 with JavaScript (AJAX)

I have developed a Symfony2 RESTful webservice prototype that is still a work in progress. I am looking for guidance on how clients can send JSON data or consume JSON data from this webservice. Essentially, I need examples of how to send requests or post d ...

In case of an API error with the Nuxt fetch method, ensure that the entire site responds with a 404

Is it possible to configure a Nuxt website to respond with a 404 error when the API raises a 404 error? The API call is made on the client side using the fetch method: Check out this demo here: codesandbox demo Code Snippets index.vue <template> ...

An error arises when using the command window.close()

I have encountered an issue with this code where it closes all Safari windows but works fine in Internet Explorer. What should I do? Is there an alternative method for closing the current opened window in every browser? <input type='button' v ...

ES6 does not allow the use of native setters when extending the HTMLButtonElement

Looking for a way to utilize the native setters and getters for an extended HTMLButtonElement, particularly focusing on the 'disabled' property. You can find more information about the property here: https://developer.mozilla.org/en-US/docs/Web/ ...

clearInterval function is not functioning

Could this be a simple syntax error causing my frustration? The resizeTime variable seems to persist despite multiple attempts to clear it using clearInterval. Any thoughts on what may be going wrong here? Below is the code snippet: var resizeTime; // e ...

unable to successfully npm install canvas

For my GitHub repository, please visit here This project was actively developed until November of last year, after which I did not commit any changes. Today, I attempted to run the project again but encountered the following error. My current system versi ...

React Bootstrap ToggleButton firing function multiple times unnecessarily

I've encountered an issue with my react-bootstrap ToggleButtons. Whenever I click on them, the handlePlatformChange() function is triggered twice - first with the correct id and then immediately after with null. I tried including e.preventDefault() in ...

Navigating to a new view in AngularJS following a successful authentication with Firebase

After successfully logging in and authenticating through Firebase, I am looking to direct users to a specific view. app.controller('PageCtrl', function ($scope, $location, $http ) { $scope.logIn = function(){ var email = $('#logi ...

What is the best way to select a specific value from JSON (Webhook) Data?

I am looking for a way to extract and store a specific value from a JSON data into a variable. Specifically, I want to save the value of Name (John) in a variable like this: var name = "". I attempted using var name = data.Name but it is not wor ...

Is it possible to provide unrestricted support for an infinite number of parameters in the typing of the extend function from Lodash

I am utilizing the "extend" function from lodash to combine the objects in the arguments as follows: import { extend } from 'lodash'; const foo1 = { item: 1 }; const foo2 = { item: 1 }; const foo3 = { item: 1 }; const foo4 = { item: 1 }; const f ...

Is Cognito redirect causing issues with Angular router responsiveness?

When employing social login via AWS Cognito, Cognito sends a redirect to the browser directing it to the signin redirect URL after signing in. In this case, the specified URL is http://localhost:4200/home/. Upon receiving this redirect, the application in ...

Ava tests hitting a snag with TypeScript ("Oops! Unexpected identifier found")

Currently delving into the realms of TypeScript, I decided to venture into creating a TypeScript React application using create-react-app. This application involves a separate TypeScript file called logic.ts, which in turn imports a JSON file. import past ...

To enable the radio button upon clicking the list item in JavaScript, simply check the radio button

I am working with radio buttons Here is the HTML code: <input type="radio" class="first" name="bright" checked> <input type="radio" class="second" name="bright" > <input type=" ...

How can I implement Jquery ajax calls in various JavaScript functions?

I'm encountering an issue with a particular function in my code function readComm(){ $.post("something.php", {read:"read"}, function(data){ retVal = $.trim(data).toString(); console.log(retVal); return retVal; }); } T ...

Steps to indicate a selected check column in a grid

I am working with a grid that has a check column, and I need to programmatically mark the checkbox. This is how the check column is coded: columns: { items:[ { itemId: 'checkColumn', xtype: 'selectallche ...

Import a new JavaScript file and access a variable

I'm currently working on a school project where I am creating an online platform for purchasing games. The platform is designed using HTML, CSS, and JS, with each game having its own corresponding JS file containing the information. Here is a sample o ...

Tips for adding React components to an array with the help of backticks

Currently, I am attempting to populate an array with icons by extracting the name from data and concatenating "<" and "/>" around it in order to convert it into an Mui Icon. Despite renaming the imported icons to match the names in the data, when I ...

Personalize the appearance of dynamically generated DIV elements

This script generates a random number of squares (ranging from 20 to 40) and adds text to each square. The script then calculates the width of each square so that they all fit in a single row. Here is the code snippet: var quantity = Math.floor(Math.ran ...