JavaScript Snippet – Fancy getKeys

Most of us know the simple way to get the keys from an object in JavaScript (~61 bytes after minified):

function getKeys(obj) {
    var k = [];
    for (var i in obj) {
        k.push(i);
    }
    return k;
}

But how many of us knew that array assignment within the for-in loop would work? (~58 bytes after minified)

function getKeys(obj) {
    var i = 0, k = [];
    for (k[i++] in obj) {}
    return k;
}

To be honest I cant take the credit for this because I actually found it here. Even though knowing this may rarely help you shorten your code, this is still a pretty cool capability! 8-)

WARNINGS:

  • The above defined getKeys function is really just to prove that you can do for(anArray[counter++] in anObject)....
  • If you can be certain that Object.keys will be defined in the environment in which your code will run, you should use that native function instead.
  • Using this function as is will include prototypal properties defined for the class of the object passed.
  • This function will not return properties that override prototypal properties (such as toString) in some environments.

6 thoughts on “JavaScript Snippet – Fancy getKeys”

    1. That is the best way as long as you know that Object.keys exists in the environment that your code will be running. To tell you the truth, this post is really to let everyone know about the fact that you can assign the value directly to the array value within the expression as if it were on the left-hand side of an assignment expression.

  1. That would also include the properties in the prototype.
    Since most of the time that is not required, why not just use Object.keys(obj) ?

Leave a Reply

Your email address will not be published. Required fields are marked *


3 × = twenty one

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="">