Created
November 29, 2022 02:55
-
-
Save funnyzak/a0655c6a08536f814809383b59e16c43 to your computer and use it in GitHub Desktop.
Replace all values of the string type of the object with the target value
This file contains hidden or 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
objectDeepReplace = (obj, searchRegex, replaceValue) => { | |
for (const key in obj) { | |
if (typeof obj[key] === 'string') { | |
obj[key] = obj[key].replace(searchRegex, replaceValue); | |
} else if (typeof obj[key] === 'object') { | |
objectDeepReplace(obj[key], searchRegex, replaceValue); | |
} | |
} | |
return obj; | |
}; | |
const demoObject = { | |
hi: 'Hello world!', | |
hello: ['Hello World!', 'Hello,friend!'], | |
say: { | |
hi: 'Hello world!', | |
hello: ['Hello World!', 'Hello,friend!'], | |
}, | |
}; | |
console.log(objectDeepReplace(demoObject, /Hello/g, 'Helloo')); | |
// follow is the output: | |
// {"hi":"Helloo world!","hello":["Helloo World!","Helloo,friend!"],"say":{"hi":"Helloo world!","hello":["Helloo World!","Helloo,friend!"]}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment