Skip to content

Instantly share code, notes, and snippets.

@shchegol
Last active March 6, 2021 19:52
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 shchegol/dd2d4d43bd0db5790bceafe15e60e285 to your computer and use it in GitHub Desktop.
Save shchegol/dd2d4d43bd0db5790bceafe15e60e285 to your computer and use it in GitHub Desktop.
Object iterate
Object clone
Is object empty?
// #### 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
// 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');
}
### 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