Skip to content

Instantly share code, notes, and snippets.

@nainglinaung
Last active December 27, 2017 09:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nainglinaung/dd05b36287c9b8984d4d86cfb29b8614 to your computer and use it in GitHub Desktop.
Save nainglinaung/dd05b36287c9b8984d4d86cfb29b8614 to your computer and use it in GitHub Desktop.
Javascript Object Merger with ES6
mergeObject: (obj1 = {}, obj2 = {}) => {
let ObjArray = [obj1,obj2];
let key1 = Object.keys(obj1);
let key2 = Object.keys(obj2);
let unionKeys = [...new Set([...key1 ,...key2])];
let ignore = new Set(['createdAt','updatedAt','updated_at','_id']);
let result = {};
let keysMap = new Map();
unionKeys = new Set([...unionKeys].filter(x => !ignore.has(x)));
for (var key of unionKeys) {
if (Object.prototype.hasOwnProperty.call(obj2, key)) {
keysMap.set(`${key}-${utiliy.typechecker(obj2[key])}`,0);
} else {
keysMap.set(`${key}-${utiliy.typechecker(obj1[key])}`,1);
}
}
// console.log('start')
for (var [key, from] of keysMap.entries()) {
let [index,type] = key.split('-');
if (type == 'string' || type == 'number' ) {
result[index] = ObjArray[1][index];
if (!result[index]) {
result[index] = ObjArray[0][index];
}
} else if (type == 'array') {
let array1 = ObjArray[0][index] || [];
let array2 = ObjArray[1][index] || [];
result[index] = [...new Set([...array1 ,...array2])];
continue;
} else if (type == 'object') {
let subObj1 = ObjArray[0][index] || {};
let subObj2 = ObjArray[1][index] || {};
result[index] = utiliy.mergeObject(subObj1,subObj2);
}
}
return result;
},
isEmptyObject : (obj) => {
return !Object.keys(obj).length;
},
typechecker: (obj) => {
return (typeof(obj) === 'object') ? (Array.isArray(obj)) ? 'array' : 'object' : typeof(obj);
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment