Skip to content

Instantly share code, notes, and snippets.

@iAmShakil
Last active January 22, 2018 18:47
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 iAmShakil/17a05549f7d17713bf5b443d4cda9614 to your computer and use it in GitHub Desktop.
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
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