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! šŸ˜Ž

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.
Categories: BlogJavaScriptJScript

6 Comments

ksmithut · July 10, 2014 at 1:57 PM

If you’re not worried about IE8 support, why not just use

Object.keys(obj);

    Chris West · July 10, 2014 at 3:40 PM

    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.

chris-l · July 10, 2014 at 2:04 PM

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) ?

Paul Spaulding · July 10, 2014 at 2:55 PM

Most browsers support Object.keys:

[code language=javascript]
var obj = {a:1, b:2, c:3};
Object.keys(obj);
// ["a", "b", "c"]
[/code]

s · July 10, 2014 at 3:00 PM

Object.keys() is fancier.

    Chris West · July 10, 2014 at 3:45 PM

    LOL, by fancy I mean interesting. I really just wrote the post to show the ability to do this in JS:
    [code language=javascript]
    for(anArray[counter++] in anObject);
    [/code]

Leave a Reply to ksmithut Cancel reply

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