-4

This is a kind of strange question but is there a way to set a key to be the "first" key in an object?

For example say I have an object:

object = {
 'name': bob,
 '3': 3,
 'id': 1
}

And if I call Object.getOwnPropertyNames(object), is there a way I can fix the order to be something like ['id', '3', 'name']?

Tim
  • 2,221
  • 6
  • 22
  • 43
  • 5
    Properties don't really have a usable ordering in JavaScript. The current spec says that the properties should be returned (by `Object.keys()` for example, or a `for ... in` loop) in the order in which they were created, but relying on that in an actual body of code is highly fragile. – Pointy Sep 13 '18 at 22:35
  • 2
    You can just `getOwnPropertyNames()` and then sort them out. Or you technically can (**but please don't**) override `getOwnPropertyNames` with your own implementation, which will call native implementation. In general, it is a strange question indeed :) – Yeldar Kurmangaliyev Sep 13 '18 at 22:35
  • 3
    Right the most robust thing to do is impose your own ordering via some reliable external mechanism depending on your application. – Pointy Sep 13 '18 at 22:36
  • 1
    Thanks for the input everyone! – Tim Sep 13 '18 at 22:37
  • 1
    It isn't at all a strange question :) there are plenty of times you want to do that. Just `sort` the properties after you call `.getOwnPropertyNames` – Jared Smith Sep 13 '18 at 22:37
  • 1
    If you need an ordered dictionary well-defined by the spec, use a [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) – Patrick Roberts Sep 13 '18 at 22:42

2 Answers2

1

Properties order in objects is not guaranteed in JavaScript. details: Does JavaScript Guarantee Object Property Order?

UPD: Take a look at maps ref: https://hackernoon.com/what-you-should-know-about-es6-maps-dc66af6b9a1e

Nikolay Vetrov
  • 624
  • 6
  • 17
0

You can use a array order, then use map:

var object = {
 'name': 'bob',
 '3': 3,
 'id': 1
};
var order = ['id', '3', 'name'];
var result = order.map((current,index,order)=>{
    return object[order[index]];
},0);
console.log(result);
protoproto
  • 2,081
  • 1
  • 13
  • 13