forked from vasanthk/js-bits
-
Notifications
You must be signed in to change notification settings - Fork 0
/
object-clone.js
62 lines (54 loc) · 1.68 KB
/
object-clone.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
/**
* Object copy by value (Clone)
*
* @Reference:
* http://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-clone-an-object/
* http://stackoverflow.com/a/728694/1672655
*/
(function () {
var obj = {
name: 'vasa',
role: 'Ninja'
};
// A trick to clone an object (or copy by value)
var clonedObj = JSON.parse(JSON.stringify(obj));
// In ES6
var clone = Object.assign({}, obj);
// With jQuery
// Shallow copy
var copiedObjShallow = jQuery.extend({}, obj);
// Deep copy
var copiedObjDeep = jQuery.extend(true, {}, obj);
// Object.assign() polyfill
// http://stackoverflow.com/a/34283281/1672655
if (!Object.assign) {
Object.defineProperty(Object, 'assign', {
enumerable: false,
configurable: true,
writable: true,
value: function (target) {
'use strict';
if (target === undefined || target === null) {
throw new TypeError('Cannot convert first argument to object');
}
var to = Object(target);
for (var i = 1; i < arguments.length; i++) {
var nextSource = arguments[i];
if (nextSource === undefined || nextSource === null) {
continue;
}
nextSource = Object(nextSource);
var keysArray = Object.keys(nextSource);
for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
var nextKey = keysArray[nextIndex];
var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
if (desc !== undefined && desc.enumerable) {
to[nextKey] = nextSource[nextKey];
}
}
}
return to;
}
});
}
})();