Created
November 29, 2015 19:46
-
-
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)
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
/** | |
* 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; | |
} |
@cdelgadob thanks for that!
FYI: You can do it with lodash like this:
_.cloneDeepWith(object, value => value === prevVal ? newVal : undefined)
.
@ypresto as I would do, if instead of passing fn(prevVal, newVal, object)
, I would always have to pass inside an array with 1 object or more, example fn([{prevVal: 'old value', newVal: 'new value' }], object)
I liked your solution because it is cleaner.
Great solution @cdelgadob!
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
You could also use the
reviver
function using JSON.parse. It's quite efficient too. i.e.: