Recursion and replacing strings
- Javascript
What if you needed to write a function that will replace a string in a blob of JSON regardless of what shape that data might take. It could be an array of objects, an object containing arrays, a string or...you get the point. This is a great excuse to use recursion.
When the situation will not allow for a simple for loop, recursion comes to the rescue. It can be summarised as a function calling itself with new, updated arguments. This allows us to step through some JSON, passing the next node to the same function to infinity.
const replaceStringInJson = (json, callback) => {
if (Array.isArray(json)) {
return json.map((item) => replaceStringInJson(item, callback))
} else if (typeof json === 'object') {
return Object.fromEntries(
Object.entries(json).map(([key, value]) => [
key,
replaceStringInJson(value, callback),
])
)
} else if (typeof json === 'string') {
json = callback(json)
}
return json
}
const outputJson = replaceStringInJson(json, (str) => {
return str.replace('old', 'new')
})