FrozenHeart
FrozenHeart

Reputation: 20756

Do Object.keys() and Object.values() methods return arrays that preserve the same order

Do Object.keys() and Object.values() methods return arrays that preserve the same order?

I mean, suppose that we have the following object:

var obj = {};
obj.prop1 = "Foo";
obj.prop2 = "Bar";

If I call obj.keys() and obj.values() will they return properties with the same order?

prop1
prop2

Foo
Bar

or

prop2
prop1

Bar
Foo

Right?

So the following option is not possible, right?

prop1
prop2

Bar
Foo

Upvotes: 43

Views: 15772

Answers (1)

Maor Refaeli
Maor Refaeli

Reputation: 2527

In short, Yes.

Both Object.keys and Object.values (and also Object.entries()) enumerate via for-in loop on the object.
Since both use the same [[Enumerate]], as long as they are called on an object with same unchanged own prototype (without deleting or adding keys between the keys and values calls), the order will be the same.

What will the order be?
It depends on how you initialized your object, which explorer you are using, and the order of which you have inserted additional keys to the object.
If the actual order is important to you as well (and not only that both keys and values result will be in to the same order) the bulletproof approach will be to use an array.

A different approach: Object.entries() will return a list of [key, value] pairs (in the same order provided by a for-in loop as well) which might be more helpful for your use case.

Upvotes: 45

Related Questions