-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcloneObject.js
70 lines (63 loc) · 2 KB
/
cloneObject.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
=== Deep cloning and making sure only plain objects in string format are copied =====
let objectCopy = JSON.parse(JSON.stringify(object))
=====================================
const cloneObject = function (object) {
var copy = {};
var keys = Object.keys(object);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var value = object[key];
copy[key] = value;
}
return copy;
};
===============================================
function clone(src) {
function mixin(dest, source, copyFunc) {
var name, s, i, empty = {};
for (name in source) {
// the (!(name in empty) || empty[name] !== s) condition avoids copying properties in "source"
// inherited from Object.prototype. For example, if dest has a custom toString() method,
// don't overwrite it with the toString() method that source inherited from Object.prototype
s = source[name];
if (!(name in dest) || (dest[name] !== s && (!(name in empty) || empty[name] !== s))) {
dest[name] = copyFunc ? copyFunc(s) : s;
}
}
return dest;
}
if (!src || typeof src != "object" || Object.prototype.toString.call(src) === "[object Function]") {
// null, undefined, any non-object, or function
return src; // anything
}
if (src.nodeType && "cloneNode" in src) {
// DOM Node
return src.cloneNode(true); // Node
}
if (src instanceof Date) {
// Date
return new Date(src.getTime()); // Date
}
if (src instanceof RegExp) {
// RegExp
return new RegExp(src); // RegExp
}
var r, i, l;
if (src instanceof Array) {
// array
r = [];
for (i = 0, l = src.length; i < l; ++i) {
if (i in src) {
r.push(clone(src[i]));
}
}
// we don't clone functions for performance reasons
// }else if(d.isFunction(src)){
// // function
// r = function(){ return src.apply(this, arguments); };
} else {
// generic objects
r = src.constructor ? new src.constructor() : {};
}
return mixin(r, src, clone);
}