Skip to content

Instantly share code, notes, and snippets.

@steveosoule
Created July 25, 2023 16:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save steveosoule/ab1a34554f0c1c7bb956dbcfb0df3c31 to your computer and use it in GitHub Desktop.
Save steveosoule/ab1a34554f0c1c7bb956dbcfb0df3c31 to your computer and use it in GitHub Desktop.
JavaScript Tokenize Object
const tokenizeObject = (obj = {}, tokens = [], replacements = []) => {
if (!Array.isArray(tokens) || !Array.isArray(replacements) || tokens.length !== replacements.length) {
return obj;
}
const replacedJsonObj = tokens.reduce((jsonObj, token, i) => {
return jsonObj.replace(token, replacements[i]);
}, JSON.stringify(obj));
return JSON.parse(replacedJsonObj);
};
tokenizeObject({foo: '%bar%'}, ['%bar%'], ['thing']);
// {foo: 'thing'}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment