1

Given I have a object like ..

const payload = {
    prop0: 'a',
    prop1: 'b',
    prop2: 'c',
    prop3: 'd',
    prop4: 'e'
};

On doing this [...Object.values(payload)]

Will it always return

['a', 'b', 'c', 'd', 'e'];

Or can in some conditions the order be different like ['b', 'c', 'a', 'e', 'd']

Adeel Imran
  • 13,166
  • 8
  • 62
  • 77
  • JavaScript objects never guarantee the order of the keys, but you can definitely sort it to that – Sterling Archer Mar 25 '19 at 17:20
  • 1
    @SterlingArcher - Yes, they do. Have done for nearly four years. (**Don't** read that as an endorsement of anyone actually **using** the order. :-) ) – T.J. Crowder Mar 25 '19 at 17:26
  • @T.J.Crowder it's good to know that's been changed, but the dupe that was linked specifies that in the answers it seems. Any reason you re-opened this to answer it instead of adding more relevant details to the duplicate? – Sterling Archer Mar 25 '19 at 17:33
  • @SterlingArcher - Because my brain misfired and I thought the answer for `Object.values` was different from the answer for `for-in`, which is what the answers there focus on. But I'm wrong. If you can re-dupehammer, that'd be great. – T.J. Crowder Mar 25 '19 at 17:36
  • @T.J.Crowder no worries, happens to me a lot too! :) I don't have a gold badge or remaining close votes, but https://stackoverflow.com/questions/30076219/does-es6-introduce-a-well-defined-order-of-enumeration-for-object-properties is the proper, up to date duplicate – Sterling Archer Mar 25 '19 at 17:37
  • 1
    @Adeel - No, you can't rely on the order of `Object.values`. It uses the spec's [EnumerableOwnPropertyNames](https://tc39.github.io/ecma262/#sec-enumerableownpropertynames) operation. Although that uses [[OwnPropertyKeys]], which would provide ES2015 order, it explicitly then says that the order should be rearranged to whatever implementation-dependent order `for-in` (and such) use. That order is not defined. – T.J. Crowder Mar 25 '19 at 17:38
  • 2
    @SterlingArcher - Hey, it let me dupehammer. I didn't think you could dupehammer after being the one who reopened. TIL. – T.J. Crowder Mar 25 '19 at 17:38
  • 1
    Thank you for the help guys :) You guys are awesome. – Adeel Imran Mar 25 '19 at 17:39
  • 1
    @AdeelImran anytime! Sorry it's a dupe, but there's excellent information in there that should help you. Feel free to go to https://chat.stackoverflow.com/rooms/17/javascript if you have more questions! I'm there, so you can ping me if you want – Sterling Archer Mar 25 '19 at 17:42
  • Great, again thank you so much! – Adeel Imran Mar 26 '19 at 09:19

0 Answers0