Home > Blockchain >  How to compile object inside a string?
How to compile object inside a string?

Time:04-03

I have this string:

const fullname = "my name is ${param.name}"

and this object:

const param = {
  name: 'foo'
};

Is there a way to "compile" the string with the object in typescript/javascript?

Why? I want to separate the data from the schema (string).

Both are in separate files so I can't just do: my name is ${param.name}.

I have a function that takes the string and the object and make the output. but there is something like this exist?

The result I expect is:

`my name is foo`

CodePudding user response:

You are looking for a template string: You can use the following syntax:

`my name is ${param.name}`

CodePudding user response:

Short answer (one line of code) - yes - it's possible

console.log(new Function('obj', 'return "hello "   obj.name')({ name: 'jackob' }))

Let's break it down to better understand what's happaned:

new Function('obj', 'return "hello "   obj.name')

This will create a new function that accepts a single parameter (as the name implies we are expecting an object). The function body is handling the object and concat it into a string (very similar to what you tried to do)

In order to run it we can use it as an anonymous function or create a reference (e.g. function delegation)

const func = new Function('obj', 'return "hello "   obj.name')

func({ name: 'jackob' }) // here we call the function with a static object as parameter

Because the function return a value (a compiled string) we can get the returned value

const value = func({ name: 'jackob' })
console.log(value)

And one last technical note: if you feel that you are going to compile expressions - I recommend JSONata (here's a specific link to your use-case). It's a great project that unifies your operations over json objects and will help you to get more support during development and in future releases.

Good luck

  • Related