Skip to content

Instantly share code, notes, and snippets.

@khoand0000
Last active December 14, 2015 12:03
Show Gist options
  • Save khoand0000/ca9d6c3bf2d917cc2cc6 to your computer and use it in GitHub Desktop.
Save khoand0000/ca9d6c3bf2d917cc2cc6 to your computer and use it in GitHub Desktop.
snippets

Remove item from json object

var a = {x: ''};
delete a.x;
delete a['x']; // same

Loop json object

var a = {x: '', y: ''};
for (var key in a) { 
  var item = a[key]; // remember key is x or y not its value
  console.log(key);
  console.log(item);
}

Loop json object (using jquery)

var a = {x: '', y: ''};
$.each(a, function(key, item){ // item = a[key];
  console.log(key);
  console.log(item);
});

Check variable is undefined

var x; // undefined
var cmp = (typeof x == typeof undefined); // true

Check object contains key

var obj = {a: ''};
var existing = 'a' in obj; // true
var existing1 = typeof obj.a != typeof undefined; // or using the way

clone array (ref: https://davidwalsh.name/javascript-clone-array)

var clone = myArray.slice(0);

The code above creates clone of the original array; keep in mind that if objects exist in your array, the references are kept; i.e. the code above does not do a "deep" clone of the array contents. To add clone as a native method to arrays, you'd do something like this:

Array.prototype.clone = function() {
	return this.slice(0);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment