Anupam
Anupam

Reputation: 8016

javascript object keys order with negative value

I was under impression that ES6 has introduced new features to get object properties in creation order using methods like Object.getOwnPropertyNames(), Reflect.ownKeys etc but while working on a problem I realised for negative keys the order is not maintained.

const object1 = {
  "-1": 'somestring',
  "3": 42,
  "2": false,
  "-3": true
};

console.log(Object.getOwnPropertyNames(object1));
// expected output: Array ["-1", "3, "2", "-3"]
// actual output: ["2", "3", "-1", "-3"]

console.log(Object.keys(object1));

What would be the correct way to get keys in creation order for such scenario?

EDIT: I dont want to sorted order, looking for creation order

Upvotes: 1

Views: 1989

Answers (2)

Monika Mangal
Monika Mangal

Reputation: 1760

This is will, in case you don't want to change the type of the keys and keep them as strings.

Object.getOwnPropertyNames(object1).sort()

Upvotes: 0

Bergi
Bergi

Reputation: 664876

Yes, the ordering of keys does distinguish between array indices (basically non-negative integers) and others. To get your keys as sorted integers, use

Object.keys(object1).map(Number).sort((a, b) => a-b)

Upvotes: 2

Related Questions