code_junkie

How to find keys of a hash?

Nov 10th, 2011
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.85 KB | None | 0 0
  1. var h = {a:'b',c:'d'};
  2.  
  3. var k = h.keys() ; // k = ['a','c'];
  4.  
  5. Object.prototype.keys = function ()
  6. {
  7. var keys = [];
  8. for(var i in this) if (this.hasOwnProperty(i))
  9. {
  10. keys.push(i);
  11. }
  12. return keys;
  13. }
  14.  
  15. var obj = { "a" : 1, "b" : 2, "c" : 3};
  16. alert(Object.keys(obj)); // will output ["a", "b", "c"]
  17.  
  18. if(!Object.keys) Object.keys = function(o){
  19. if (o !== Object(o))
  20. throw new TypeError('Object.keys called on non-object');
  21. var ret=[],p;
  22. for(p in o) if(Object.prototype.hasOwnProperty.call(o,p)) ret.push(p);
  23. return ret;
  24. }
  25.  
  26. var keys = [];
  27. for (var k in h)keys.push(k);
  28.  
  29. function getKeys(h) {
  30. Array keys = new Array();
  31. for (var key in h)
  32. keys.push(key);
  33. return keys;
  34. }
  35.  
  36. _.keys({one : 1, two : 2, three : 3});
  37. // => ["one", "two", "three"]
  38.  
  39. Object.prototype.keys = function () ...
  40.  
  41. for (var key in h) ...
Add Comment
Please, Sign In to add comment