I have an object and in the scope of the current function I want to be able to turn its properties into variables of the same name.
The following code doesn't work but seem like the starting place for something like this:
let thingObject = {Thing: "Value",Thing2: "Value2"}
for ([key, value] of Object.entries(thingObject)) {
eval(`let ${key} = '${value}'`)
}
I know in the browser there is the window
object and in Node.js there is global
so if I didn't care about scope I could probably do something like:
for ([key, value] of Object.entries(thingObject)) {
global[key] = value
}
This is much better as it properly retains the type value
but I need to do this many times without polluting any global object.
Object destruction syntax would do the trick with something like:
let {Thing, Thing2} = thingObject
Except I don't know the keys ahead of time.
This answer to another question seems relevant but I am struggling to make use of it to solve this problem.
How can I create variables from properties of an object without knowing the property names within the current scope?
Context:
This is used to process templates where the creators of the templates will use template literals like `${Thing}-other stuff/${Thing2}`
.
They will then call my generic function passing in an object that contains properties for each of the variables they used in the template.
They will both know the names when calling my function and reference those names in their template but my code in between will be generalized not to care about either side.
The reason to use variables is to make the templates cleaner as having to include the name of some variable container object in the templates makes them more verbose than needed, Ex: `${VariablesObject.Thing}-other stuff/${VariablesOjbect.Thing2}`
.