Last active
February 24, 2025 09:24
-
-
Save bhaireshm/984b30cd47d97866de4bf9e8090bd6df to your computer and use it in GitHub Desktop.
Merge two objects using JavaScript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.