r/javascript • • Oct 14 '16

help Object.keys vs. for...in, which do you prefer and which is more performant?

1 Upvotes

15 comments sorted by

1

u/ShippingIsMagic Oct 14 '16

I thought keys was more like for..of than for..in ?

1

u/PitaJ Oct 15 '16

for...of works on interators. Object.keys returns an array of object keys, so you use it like this:

Object.keys(obj).forEach(key => obj[key].dosomething());

You can use Object.keys with for...of like /u/inu-no-policemen said here

1

u/ttolonen Oct 14 '16

They are different animals: Object.keys just returns Object's own enumerable, not-inherited properties in an Array. for... in will actively iterate over own enumerable properties of the Object from the full prototype chain as they currently are, which includes inherited properties and possibly changes to object during the loop. That means hard to spot bugs can be created, if the keys are added or deleted during for..in -loop. In this sense it is usually safer to first get the keys with Object.keys and then iterate over Object using that result.

1

u/[deleted] Oct 15 '16

[removed] — view removed comment

0

u/ttolonen Oct 15 '16

The performance difference is not significant, and they do different things, so no reason to compare unless you know the data and what should be done with it.

1

u/ishmal Oct 16 '16

I prefer Object.keys, since it produces an array, so you can then chain things together in a functional style:

let myStuff = Object.keys(object).filter(s => s.startsWith("pickle")).map(it => it.name). etc, etc.....

I am no Functional Bolshevik, but it does have its charms.

0

u/fire_code !expert Oct 14 '16

I prefer for...in; it's a little more verbose, but is easier to reason about when scanning and/or debugging/rereading code.

That said, for...in and Object.keys(myObject).forEach are practically the same thing; just depends on the individual.

Also, how would you use reduce on an object's keys if they are strings?

3

u/inu-no-policemen Oct 14 '16
for(let key of Object.keys(foo)) {
  console.log(key, foo[key]);
}

Some day (probably):

for(let [key, value] of Object.entries(foo)) {
  console.log(key, value);
}

1

u/[deleted] Oct 15 '16

Also, how would you use reduce on an object's keys if they are strings?

Why wouldn't you be able to?

Object.keys(things).reduce((prev, curr)=> {
    if (someRequirement)
        prev[curr] = things[curr];

    return prev;
}, {});

Using Object.keys and .reduce we implemented a .filter on on object.

1

u/fire_code !expert Oct 15 '16

Gotcha. I'm not super involved with these more programmatic aspects of JS. Thanks!

0

u/[deleted] Oct 15 '16

[deleted]

1

u/[deleted] Oct 15 '16

[removed] — view removed comment

1

u/PitaJ Oct 15 '16

No it won't.