Skip to content

Instantly share code, notes, and snippets.

@flipace
Created November 29, 2015 19:46
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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;
}
@leebenson
Copy link

typeof(val) === 'array'

typeof [] always === object, so this OR check is redundant.

@ypresto
Copy link

ypresto commented Jun 1, 2018

FYI: You can do it with lodash like this: _.cloneDeepWith(object, value => value === prevVal ? newVal : undefined).

@cdelgadob
Copy link

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;
}
})

@TunaYagci
Copy link

@cdelgadob thanks for that!

@GlauberF
Copy link

GlauberF commented Dec 3, 2019

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.

@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