Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

175
Views
JS how to render a template from a object

I have a string template such as:

template = `<li>${name}<li><li>${address}<li><li>${sex}<li>`

I have defined a object {name: "tom", address: "usa", sex: "male"} in js file.

how can I render the template by the object directly? to get result as:

<li>tom<li><li>usa<li><li>male<li>
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

:)

var obj = {name: "tom", address: "usa", sex: "male"};
var result;
with(obj)
    result = `<li>${name}<li><li>${address}<li><li>${sex}<li>`

or

var obj = {name: "tom", address: "usa", sex: "male"};
var template = "<li>${name}<li><li>${address}<li><li>${sex}<li>";
var result = template.replace(/\${(\w+)}/g, function($0, $1) {
    return obj[$1];
});
about 4 years ago · Juan Pablo Isaza Report

0

Use the template literal when you access the object

I also had to fix your HTML to close the LIs

const arr = [
{ name: "tom", address: "usa", sex: "male" },
{ name: "lisa",address: "usa", sex: "female"}
];

document.getElementById('ul').innerHTML = arr
  .map(({ name, address, sex}) => `<li>${name}</li><li>${address}</li><li>${sex}</li>`)
  .join("")
<ul id="ul"></ul>

about 4 years ago · Juan Pablo Isaza Report

0

Just add obj. in the template and it should work.

var obj = {name: "tom", address: "usa", sex: "male"};
var template = `<li>${obj.name}<li><li>${obj.address}<li><li>${obj.sex}<li>`;
console.log(template);
// <li>tom<li><li>usa<li><li>male<li>

or you can destructure the object like so:

var obj = {name: "tom", address: "usa", sex: "male"};

// destructure
const { name, address, sex } = obj;

var template = `<li>${name}<li><li>${address}<li><li>${sex}<li>`;
console.log(template);
// <li>tom<li><li>usa<li><li>male<li>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!