Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace Dynamic string template variable with json object

I am having sample template like below i want to replace school, babydet.name,dept,babydet.section.secname with json object values how to do this please help me to solve this.

var Template1 = 'Welcome to the {{school}} baby {{babydet.name}}'
var Template2 = 'Welcome to the school {{school}} department {{dept}} babydetails {{babydet.name}} {{babydet.section.secname}}'

const namelist1= [{school:'GOVSchool',babydet: { name: 'shanker' }}];
const namelist2= [{school:'GOVSchool',dept:'CS',babydet: { name: 'shanker',section:{sectname:'A Section'}}}];

with help of string replace need to achieve this(single logic). Output want like this "Welcome to the world baby shanker"

like image 668
user7620655 Avatar asked Dec 20 '25 22:12

user7620655


1 Answers

If by any chance that lodash.js is available, you can use the _.template function for it. More details here.

var Template1 = 'Welcome to the {{school}} baby {{babydet.name}}'
var Template2 = 'Welcome to the school {{school}} department {{dept}} babydetails {{babydet.name}} {{babydet.section.secname}}'

var namelist1= [{school:'GOVSchool',babydet: { name: 'shanker' }}];
var namelist2= [{school:'GOVSchool',dept:'CS',babydet: { name: 'shanker',section:{sectname:'A Section'}}}];

_.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
var interpolator = _.template(Template1);
var interpolated = interpolator(namelist2[0]);

console.log(interpolated)

interpolator = _.template(Template2);
interpolated = interpolator(namelist2[0]);

console.log(interpolated)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
like image 123
Adrian Avatar answered Dec 22 '25 12:12

Adrian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!