I want to create a javascript object from a template. The problem is that I donโt know how the template will look in advance. As a simple example, if I had a template function
template = function (data) { return { title: data.title } }
then I could run template({ title: "Steve" }) and return the object
{ title: "Steve" }
Because data.title not evaluated until I call the template function. But I am building an object based on user input, where the field names are unknown in advance and can be deeply nested anywhere in the object.
If I define an object that is returned in advance, then the data.title field in this example will already be evaluated and will not use the input data. For example, I want to be able to define a template object, for example
obj = { title: this.title }
then redefine the template as
template = function () { return obj }
and call template.call({title:"Steve"}) . But now I'm coming back
{ title: undefined }
because this.title already rated when I defined obj . Perhaps I am approaching this incorrectly because I continue to come to the conclusion that I will have to change the function, strict it, modifying the line to include the this.title code and creating a new function from the line. But this seems like a simple terrible idea.
And moving an object looking for special values โโto replace seems expensive and complicated. I was also looking for some kind of javascript template library but didn't find anything.
EDIT: To make it more clear that the input and template structure do not necessarily match, maybe I have a template that looks like
template = function (data) { return { name: "Alfred", stats: { age: 32, position: { level: 10, title: data.title } } } }
and call template({title:"Manager"}) to get
{"name": "Alfred", "stats": {"age": 32, "position": {"level": 10, "title": "manager"}}}