-
-
Save flipace/bed6b89aed5cb0e19cde to your computer and use it in GitHub Desktop.
/** | |
* 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; | |
} |
FYI: You can do it with lodash like this: _.cloneDeepWith(object, value => value === prevVal ? newVal : undefined)
.
You could also use the reviver
function using JSON.parse. It's quite efficient too. i.e.:
JSON.parse(JSON.stringify(object), (key, value) => {
if (key=='propToChange') {
return newValue;
} else {
return value;
}
})
@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).
typeof []
always ===object
, so this OR check is redundant.