Last active
March 6, 2021 19:52
-
-
Save shchegol/dd2d4d43bd0db5790bceafe15e60e285 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
Object iterate | |
Object clone | |
Is object empty? |
This file contains hidden or 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
// #### JSON clone. If you don`t have a methods. | |
var cloneOfA = JSON.parse(JSON.stringify(a)); | |
// #### Jquery | |
// Shallow clone | |
var newObject = jQuery.extend({}, oldObject); | |
// Deep clone | |
var newObject = jQuery.extend(true, {}, oldObject); | |
// #### Deep clone | |
Object.clone = function clone(o, copyProto, copyNested){ | |
function Create(i){ | |
for(i in o){ | |
if(o.hasOwnProperty(i)) this[i] = ( copyNested && typeof o[i] == "object" ) | |
? clone(o[i], true, true) : o[i]; | |
} | |
} | |
if(copyProto && "__proto__" in o) Create.prototype = o.__proto__; //IE buggy | |
return new Create(); | |
} | |
//o - target object | |
//copyProto - if we need to copy prototype | |
//copyNested - if we need to copy nested objects | |
var target = { | |
"A" : { | |
"Z" : 1, | |
"X" : 2, | |
"Y" : { | |
"F" : 3, | |
"G" : 4 | |
} | |
} | |
}; | |
target.__proto__.f = function(){}; | |
var clone1 = Object.clone(target, false, true); | |
clone1.f //undefined | |
clone1.A == target.A //false | |
var clone2 = Object.clone(target, true); | |
clone2.f //function | |
clone2.A == target.A //true |
This file contains hidden or 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
// works fine in most browsers | |
if (Object.keys(obj).length == 0) { | |
console.log('empty'); | |
} | |
// stable | |
function isEmptyObject(obj) { | |
for (var i in obj) { | |
if (obj.hasOwnProperty(i)) { | |
return false; | |
} | |
} | |
return true; | |
} | |
// jquery | |
if ($.isEmptyObject({});) { | |
console.log('empty'); | |
} |
This file contains hidden or 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
### by recursion | |
function recursive(obj) { | |
for(let key in obj) { | |
if(typeof obj[key] === 'object') { | |
recursive(obj[key]) | |
} else { | |
// do something with obj[key] | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment