Last active
January 22, 2018 18:47
-
-
Save iAmShakil/17a05549f7d17713bf5b443d4cda9614 to your computer and use it in GitHub Desktop.
the following function takes the first argument as the base object and adds the following object arguments' items to it. Utilizes es6's spread operator
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
function mergeObjects(obj, ...others) { | |
// returning the base object unchanged if no other arguments are provided | |
if (others.length < 1) return obj; | |
// looping through the arguments | |
for (i = 0; i < others.length; i++) { | |
let theObj = others[i]; | |
// if the current object is not an object or its value is null (typeof null is "object" in js), then console log the error | |
if (typeof theObj !== "object" || typeof theObj === null) { | |
console.log(theObj + " is not a JavaScript object"); | |
} else { | |
for (key in theObj) { | |
if (!obj.hasOwnProperty(key)) { | |
obj[key] = theObj[key]; | |
} | |
} | |
} | |
} | |
return obj; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment