Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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 
like image 521
FrozenHeart Avatar asked Jan 20 '17 10:01

FrozenHeart


People also ask

Does object keys always return same order?

YES (but not always insertion order). Most Browsers iterate object properties as: Integer keys in ascending order (and strings like "1" that parse as ints) String keys, in insertion order (ES2015 guarantees this and all browsers comply)

What type of values does a Keys method returns when applied on an object?

keys() method is used to return an array whose elements are strings corresponding to the enumerable properties found directly upon an object. The ordering of the properties is the same as that given by the object manually in a loop is applied to the properties.

Are objects in JS ordered?

To illustrate that JavaScript object keys are not ordered, let's compare them to an array: a simple list of items in a specific order. JavaScript arrays have a defined order from index 0 to the last item in the list, and items added to the array using . push() stay in the order they are added in.

Can object have same keys?

No, JavaScript objects cannot have duplicate keys. The keys must all be unique.


1 Answers

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.

like image 133
Maor Refaeli Avatar answered Oct 14 '22 14:10

Maor Refaeli