Skip to content

Instantly share code, notes, and snippets.

@flipace
Created November 29, 2015 19:46
Show Gist options
  • Save flipace/bed6b89aed5cb0e19cde to your computer and use it in GitHub Desktop.
Save flipace/bed6b89aed5cb0e19cde to your computer and use it in GitHub Desktop.
Deep replace a value within an object or array (using lodash or underscore)
/**
* Deep search and replaces the given property value "prevVal" with "newVal"
* @param {any} prevVal [description]
* @param {any} newVal [description]
* @param {object|array} object the original object or array in which the values should be replaced
* @return {object|array} the new object or array
*/
function replacePropertyValue(prevVal, newVal, object) {
const newObject = _.clone(object);
_.each(object, (val, key) => {
if (val === prevVal) {
newObject[key] = newVal;
} else if (typeof(val) === 'object' || typeof(val) === 'array') {
newObject[key] = replacePropertyValue(prevVal, newVal, val);
}
});
return newObject;
}
@andymeek
Copy link

Great solution @cdelgadob!

@tschneid
Copy link

tschneid commented Feb 17, 2021

You could also use the reviver function using JSON.parse. It's quite efficient too. i.e.:

Note that JSON.parse(JSON.stringify(object))) has some side effects, such as converting dates into strings (see here).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment