Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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: {...}}}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement