×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Javascript
Posted by: Paul Zz
Added: Feb 21, 2017 5:59 AM
Modified: Feb 21, 2017 7:37 AM
Views: 8
Tags: clone object
Clones the input object. Returns false if there is something wrong with it
  1. /**
  2.  * Creates a clone of the input object. <br>
  3.  * To avoid unexpected results, one should not use this function to clone <b>arrays</b>.<br>
  4.  * If you want to be able to clone object with <b>null</b> prototype, remove the
  5.  * corresponding statement below (see the comments).
  6.  * @param {Object} obj
  7.  * @returns {Object|Boolean} Returns new object or false if the input value is not a valid object.
  8.  */
  9. function objectClone(obj) {
  10.     if (typeof obj !== 'object') {
  11.         return false; // not an object
  12.     }
  13.     if (!obj.__proto__) { // remove this statement to be able to clone object with __proto__ === null
  14.         return false; // has not prototype
  15.     }
  16.     if (typeof obj.__proto__ !== 'object') {
  17.         return false; // prototype is not an object
  18.     }
  19.     let result = Object.create(obj.__proto__);
  20.     for (let key in obj) {
  21.         if (!obj.hasOwnProperty(key)) {
  22.             continue;
  23.         }
  24.         result[key] = obj[key];
  25.     }
  26.     return result;
  27. }