I have an object with data and a string that works as a template, the purpose is to map the object's data into the string's variables. This is an example of my string:
const menu = {
breakfast: {
description:'something'
}
meal: {
description: 'anotherSomething'
}
}
const template = `<div>
<ul>
<li>
%breakfast.description%
</li>
<li>
%meal.description%
</li>
</ul>
</div>
`
Obviously the simplest solution would be to create an array of the string variables and map the keys from my object, concatenate them and replace them like so:
const myVariablesFromTemplate = ['breakfast.description', 'meal.description']
const myKeysToMap = {}
Object.keys(menu).forEach((item)=>{
Object.keys(menu[item]).forEach((subItem)=>{
const myNewKey = `${item}.${subItem}`
myKeysToMap[myNewKey] = menu[item][subItem]
})
})
for(let key in myVariablesFromTemplate ){
template.replace(key, myKeysToMap[key])
}
But I'm looking for a more elegant solution, where I could use javascript in the string dynamically and just access the object like in a template literal but I don't know if that's even possible. My method is not very robust, I hope you guys can help!