Skip to content

Instantly share code, notes, and snippets.

@bhaireshm
Last active February 24, 2025 09:24
Show Gist options
  • Save bhaireshm/984b30cd47d97866de4bf9e8090bd6df to your computer and use it in GitHub Desktop.
Save bhaireshm/984b30cd47d97866de4bf9e8090bd6df to your computer and use it in GitHub Desktop.
Merge two objects using JavaScript.
/**
* Merges Obj1 data into Obj2.
*
* @param {Object} obj1
* @param {Object} obj2
* @returns merged object
*
* @example
* const a = {v : [1,2]};
* const b = {v: [3]}
*
* console.log({...a, ...b}, mergeObjects(a,b));
* console.log({...b, ...a}, mergeObjects(b,a));
*/
function mergeObjects(obj1, obj2) {
const o1 = { ...obj1 }, o2 = { ...obj2 };
for (const key in o1) {
if (o1.hasOwnProperty(key)) {
if (Array.isArray(o2[key]) && Array.isArray(o1[key])) {
o2[key] = [...o1[key], ...o2[key]];
continue;
}
if (typeof o2[key] === "object" && typeof o1[key] === "object") {
o2[key] = mergeObjects(o1[key], o2[key]);
continue;
}
o2[key] = o1[key];
}
}
return o2;
}
@bhaireshm
Copy link
Author

ez.js is more than just a library; it's a coding companion that simplifies complex tasks. Whether you're dealing with arrays, numbers, objects, or strings, ez.js has got your back! Say goodbye to coding hassles and hello to streamlined JavaScript magic.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment