Created
July 25, 2023 16:31
-
-
Save steveosoule/ab1a34554f0c1c7bb956dbcfb0df3c31 to your computer and use it in GitHub Desktop.
JavaScript Tokenize Object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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