Skip to content

Instantly share code, notes, and snippets.

@funnyzak
Created November 29, 2022 02:55
Show Gist options
  • Save funnyzak/a0655c6a08536f814809383b59e16c43 to your computer and use it in GitHub Desktop.
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
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