When using Javascript template literals, they function properly when assigned to a variable, but they do not work when included in a JSON

Trying to get a grasp of Javascript. Let's say I have a variable declared with template literals:

        var templateObject = `Student name is ${filteredJSONExample.name} and student age is ${filteredJSONExample.age}.`

This functions correctly as shown below:

However, when dealing with JSON data that contains a template literal wrapped string as a value, it doesn't behave the same way.

var templateDataObject = [
            {"type": "template", "fields": {"template": "`Student name is ${filteredJSONExample.name} and student age is ${filteredJSONExample.age}`"}}
        ]

How can one insert variable values using template literals when the template is sourced from JSON data? Is there a correct approach to tackle this issue?

Check out the full code snippet below:

<html>
    <head>
        <title>JS Select Exercise</title>
        <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d9b5bebeb5b2b5b1e3aab7e3bee0fee0fee4abb6c777">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
    </head>
    <body>
        <div class="container">
            <hr/>
            <div class="row">
                <div class="col-lg-6">
                    <div class="card">
                        <div class="card-body">
                            <select class="form-control" id="select_demo" onchange=onKidChange(this)></select>
                            <br/>
                            <h3 id="agevalue"></h3>
                            <br/>
                            <h3 id="statement"></h3>
                            <button class="btn btn-sm btn-primary" onclick=printStatement()>Print Statement</button>
                            <br/><br/>
                            <button class="btn btn-sm btn-info" onclick=printAnotherStatement()>Print Another Statement</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </body>
    <script>
        var jsonDataObject = [
            {"model": "A", "identifier": 1, "fields": {"name": "Stan", "age": "12"}},
            {"model": "B", "identifier": 2, "fields": {"name": "Brett", "age": "14"}}
        ]
        
        var filteredJSONExample = jsonDataObject[0]['fields']
        
        var templateDataObject = [
            {"type": "template", "fields": {"template": "`Student name is ${filteredJSONExample.name} and student age is ${filteredJSONExampl...

// Error: text too long for AI to rewrite 

Your help on this matter is highly appreciated!

Answer №1

When you create:

"`Greetings, my name is ${name}`"

It's a simple traditional string with content:

`Greetings, my name is ${name}`

No fancy formatting, no special functionality. It's just a basic string with some variable information.

JSON & template literals don't really mix well because JSON properties need to be plain strings, not templates. So typically, you should keep them separate when working with data.

If you need to dynamically insert values into standard strings, one approach is to use placeholders and then replace them with the desired content. Here's an example:

const message = "Greetings, my name is $name$!";

message.replaceAll("$name$", "Sarah");
// Greetings, my name is Sarah!

The Chrome extensions API follows this same method for internationalization. You can check out the structure of the underlying JSON in the documentation for more details.

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

Building Silent Authentication in React Native with the help of Auth0: A Step-by-Step Guide

I am currently working on my first React Native app, and I have integrated Auth0 for authentication purposes. My goal is to implement silent authentication using refresh tokens. So far, I have attempted to use the checkSession() method but encountered an ...

AngularJS encountered an unidentified provider: $routeProviderProvider

I've hit a roadblock with an unfamiliar provider error and can't seem to figure out what I'm missing. Here's the setup: in main.js 'use strict'; angular.module('myApp') .controller('MainCtrl', ['n ...

Tips for concealing XHR Requests within a react-based single page application

Is there a way to hide the endpoint visible in Chrome's devtools under the network tab when data is fetched in React? Can server-side rendering solve this issue? ...

The Drop Down Menu feature in Bootstrap is malfunctioning within the context of a NextJS project

I've built a NEXT.JS application using VS Code. The issue I'm facing is with the drop down menu in the navigation bar - it's not sliding down to display the menu when clicked. Here is the code I'm working with: const loggedRouter = () ...

Utilize AngularJS ngResource to transmit JSON data to the server and receive a response

My Angular JS application requires sending data to the server: "profile":"OLTP", "security":"rsh", "availability":"4", "performance": { "TRANSACTION_PER_SEC":1000, "RESPONSE_TIME":200, "CONCURRENT_CONNECTION_COUNT":500, "STORAGE_SIZE": ...

Merging two distinct arrays of objects in JavaScript can be achieved by utilizing various methods and

I have a challenge where I need to merge two arrays of objects in a nested way. var array1=[{ PersonalID: '11', qusetionNumber: '1', value: 'Something' }, { PersonalID: '12', qusetionNumber: '2& ...

I encountered an issue with Material UI tabs showing the error message: "Failed prop type: The prop `children` is not supported. Please remove it."

Recently, I started using Material UI tabs in my project for the first time. Everything seems to be working fine except for one issue that keeps showing up in the console while running the project: Failed prop type: The prop `children` is not supported. Pl ...

Utilizing the Kraken.com API to create a message signature with AngularJS

I'm currently tackling Angular2 and for my first project, I want to tap into the Kraken.com API. (I know, I could have chosen an easier task :) The "Public" calls are working smoothly, but I've hit a snag with the "Private" methods. (Those requi ...

Exploring data retrieval from nested arrays of objects in TypeScript/Angular

I have an API that returns an object array like the example below. How can I access the nested array of objects within the JSON data to find the role with roleid = 2 when EmpId is 102 using TypeScript? 0- { EmpId: 101, EmpName:'abc' Role : ...

The error message states: "An attempt was made to destructure a non-iterable object. In order for non-array objects to be iterable, they must have a [Symbol.iterator

I need to call a RTK query endpoint from a function const [getCityCode, { isLoading, error, data, isSuccess, isError }] = useLocationQuery(); const getLocationDetails = async () => { const queryItems = { latitude: lat, longitude: long }; await getC ...

Quick API response in JSON format including bytes

I've encountered an issue while using a FAST API to retrieve a mongo document with byte data. The structure of the document is as shown below: item = {"namd" : "xyz", "value1: b'\x89PNG\r\n\sla\ ...

Problem with the render() function in React

I am encountering an issue while trying to retrieve data from an endpoint. A error keeps popping up, mentioning that my render method contains an unexpected token. I would appreciate any assistance. Additionally, I am unsure if I am handling the brackets ...

AngularJS not passing date data to web API

Greetings! I am currently working on a web application using AngularJS. I have a date value in AngularJS, for example 13-10-2017. In C#, I have the following field: public DateTime LicenseExpiryDate { get; set; } When I send 13-10-2017 in an AJAX reques ...

Utilizing columns within the 'segment' element in Semantic-ui to enhance layout design

I am looking to divide the ui-segment into 3 columns and display the ui-statistics evenly. Below is the code I have used in an attempt to achieve this: <div class="ui container"> <div class="ui segment"> <h3 class="ui header"> ...

What is the process for showing a duplicate image in a dialog box once it has been selected on an HTML page?

I am experiencing an issue where the dialog box is displaying when I use the button tag, but not when I use the image tag. Can someone please assist? <img src='image.png' height='200px' widht='200px' id='1'> ...

What is the best way to create a unique custom control in Javascript, potentially utilizing jQuery?

My goal is to develop a custom control using JavaScript that includes methods, properties, and events, and can be rendered within a div element. For example, one such control could be a calendar. It would display in a div, with customizable properties for ...

Adding a <link> tag with a specific onload attribute in the <head> using Next.js

While working on a Next.js project, I am trying to include the following HTML content within the <head>: <link href="..." rel="stylesheet" media="print" onload="this.media='all'" /> The code I ...

Why do Material UI components fail to render in jsdom while using Jest?

During my UI testing using Jest/React Testing Library, I encountered a peculiar issue. In one of my components, the return statement is structured as follows: const sidebarContentUp = ( <Drawer anchor="left" onClose={onMobileC ...

When rendering in React, the output of a multidimensional object may appear as undefined

Currently experiencing a challenge with a React application that I am developing. I am attempting to display data on the screen, however, there are instances where an object key is not available. For example: <div> <TableRow> <TableCel ...

The Json parsing failed to deserialize the API response

Struggling to send a JSON to my API, I've tried various solutions but still can't figure out what's going wrong. I'm stuck on this post call function: @PostMapping(path = "ts/sts") public void saveTestStep(@RequestBody Tes ...