Skip to content

Instantly share code, notes, and snippets.

@JenniferFuBook
Last active September 5, 2019 22:47
Show Gist options
  • Save JenniferFuBook/26afd67cc269e48aad28fff40176e698 to your computer and use it in GitHub Desktop.
Save JenniferFuBook/26afd67cc269e48aad28fff40176e698 to your computer and use it in GitHub Desktop.
This is a code snippet to recursively merge javascript values.
function mergeDeep(...objects) {
// For simplicity, we ignore the cases for Date and Regex
const isObject = obj => obj && typeof obj === 'object';
return objects.reduce((prev, obj) => {
try {
Object.keys(obj).forEach(key => {
const pVal = prev[key];
const oVal = obj[key];
if (Array.isArray(pVal) && Array.isArray(oVal)) {
prev[key] = pVal.concat(...oVal);
} else if (isObject(pVal) && isObject(oVal)) {
prev[key] = mergeDeep(pVal, oVal);
} else {
prev[key] = oVal;
}
});
return prev;
} catch (rangeError) {
if (rangeError instanceof RangeError) {
console.log(rangeError.message);
}
return prev;
}
}, {});
}
mergeDeep({a: 1, b: 2}, {c: 3, d: 4}); // {a: 1, b: 2, c: 3, d: 4}
mergeDeep([{a: 1, b: 2}], [{c: 3, d: 4}]); // [{a: 1, b: 2, c: 3, d: 4}]
var object = {
y: 2,
};
var other = {};
object.x = other;
other.y = object;
mergeDeep(object, other); // {y: {y: 2, x: {...}}, x: {y: {...}}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment