Reputation: 21
So my previous question was pretty bad so I am editing this question.
I have object/json like this
{
"title": "Hello {USER}",
"description": "Today you earned {AMOUNT} dolars
}
I'm sending this data to api so it gives returns an special message. But the problem is I need to replace {USER} and {AMOUNT} without needing to get values, change it and reassign it or etc. It's like replace but for objects so without changing object and doing complicated things I can dynamicly change {USER} and {AMOUNT} User comes from the api and AMOUNT is a random number I just need to change the {} brackets without complicating things too much
Upvotes: 0
Views: 2081
Reputation: 11750
Here's an approach that uses a regular expression to locate {
KEY
}
and looks up KEY
in a dictionary to perform the replacement. I used a conservative syntax of A-Z plus underscore for the syntax of the key names.
This version returns a new object (does not change the original object).
function interpolateObject(obj, dict) {
return Object.fromEntries(Object.entries(obj).map(interpolateEntry));
}
function interpolateEntry([key, val]) {
if (typeof val !== 'string') return [key, val];
return [key, interpolateString(val, dict)];
}
function interpolateString(str, dict) {
return str.replace(/\{([A-Z_]+)\}/g, (original, key) => dict.hasOwnProperty(key) ? dict[key] : original);
}
const template = {
"title": "Hello {USER}",
"status": "You look {STATUS} today",
};
const dict = { USER: 'Mark', STATUS: 'great' };
console.log(interpolateObject(template, dict));
You could also write a version that modifies the object in-place if that's what's needed.
// Alternate approach, modifies object in place.
function interpolateObjMutate(obj, dict) {
for (const key in obj) {
if (typeof obj[key] === 'string') obj[key] = interpolateString(obj[key], dict);
}
}
Upvotes: 2
Reputation: 13078
You can use a regex
to replace the text in curly braces :
function replaceText(text, value) {
const regex = /\{.*\}/;
return text.replace(regex, value);
}
const TEXT = 'Hello {USER}';
console.log(replaceText(TEXT, 'Mark'));
Upvotes: 1
Reputation: 31992
Returns
a new string, with all matches of a pattern replaced by a replacement.
var obj = {
"title": "Hello {USER}",
"status": "You look {STATUS} today"
};
function replaceTokens(name, value, str){
return str.replaceAll("{"+name+"}", value);
}
obj.title = replaceTokens("USER", "Mark", obj.title);
obj.status = replaceTokens("STATUS", "great", obj.status);
console.log(obj);
Upvotes: 2