Skip to content

Instantly share code, notes, and snippets.

@BenAychh
Created June 2, 2017 22:14
Show Gist options
  • Save BenAychh/ca5b23eeb45fdf76271099e09808f240 to your computer and use it in GitHub Desktop.
Save BenAychh/ca5b23eeb45fdf76271099e09808f240 to your computer and use it in GitHub Desktop.
const R = require('ramda');
/**
* wanted a functional way to do this that did not modify the params
**/
function deepReplaceInObject(currentValue, newValue, objectToReplaceIn) {
const paramType = R.type(objectToReplaceIn);
if (paramType === 'Object') {
return R.keys(objectToReplaceIn).reduce((object, key) => {
const type = R.type(objectToReplaceIn[key]);
if (type === 'Object' || type === 'Array') {
return R.merge(object, {
[key]: deepReplaceInObject(currentValue, newValue, objectToReplaceIn[key]),
});
} else if (objectToReplaceIn[key] === currentValue) {
return R.merge(object, { [key]: newValue });
}
return R.merge(object, { [key]: objectToReplaceIn[key] });
}, {});
} else if (paramType === 'Array') {
return objectToReplaceIn.reduce((array, value) => {
const type = R.type(value);
if (type === 'Object' || type === 'Array') {
return [...array, deepReplaceInObject(currentValue, newValue, value)];
} else if (value === currentValue) {
return [...array, newValue];
}
return [...array, value];
}, []);
}
return objectToReplaceIn;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment