Skip to content

Instantly share code, notes, and snippets.

@atk
Forked from 140bytes/LICENSE.txt
Created June 19, 2011 16:44
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atk/1034464 to your computer and use it in GitHub Desktop.
Save atk/1034464 to your computer and use it in GitHub Desktop.
polyfill an ES5-compatibile Object.keys where needed.
Object.keys = Object.keys ||
function (
o, // object
k, // key
r // result array
){
// initialize object and result
r=[];
// iterate over object keys
for (k in o)
// fill result array with non-prototypical keys
r.hasOwnProperty.call(o, k) && r.push(k);
// return result
return r
}
Object.keys=Object.keys||function(o,k,r){r=[];for(k in o)r.hasOwnProperty.call(o,k)&&r.push(k);return r}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 Alex Kloss <alexthkloss@web.de>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "objkeys",
"description": "polyfill an ES5-compatibile Object.keys where needed.",
"keywords": [
"object",
"keys",
"es5",
"polyfill"
]
}
<!DOCTYPE html>
<title>Foo</title>
<div>Expected value: <b>test, a, b, c</b></div>
<div>Actual value: <b id="ret"></b></div>
<script>
var testdata = { test: 1, a: 2, b: 3, c: 4 };
var keys = Object.keys=Object.keys||function(o,k,r){r=[];for(k in o)r.hasOwnProperty.call(o,k)&&r.push(k);return r}
document.getElementById( "ret" ).innerHTML = keys(testdata);
</script>
@Kambfhase
Copy link

There is no Object.prototype.keys in ES5 ;)

/edit:
You code fails for: {hasOwnProperty:3}

@atk
Copy link
Author

atk commented Jun 19, 2011

Sorry, got carried away by the Array stuff; hasOwnProperty is usually a prototypical method of Object, so setting it is usually a somewhat stupid idea (like naming an form input "action" or "submit". Anyway, one could use r.hasOwnProperty.call(o,k) to take care of this.

@jed
Copy link

jed commented Jul 11, 2011

hey @atk, would you mind taking the trailing comma out of your package.json keywords?

@atk
Copy link
Author

atk commented Jul 11, 2011

Not at all (same for the other gists) :)

@jdalton
Copy link

jdalton commented Aug 21, 2011

To be ES5 compatible it would also need to throw an error when o is not an object/function.

@azproduction
Copy link

Object.keys=Object.keys||function(o,r){r=[];for(r[r.length] in o);return r}

for(r[r.length] in o); - this is Beautiful! but we have to use hasOwnProperty...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment