0

I just want to ask how to get the order number of an object element, like:

{ '411510958020624384': 272216, <- 0
  '482286641982078977': 195951, <- 1
  '469176984086380574': 156025, <- 2
  '560134275538747403': 126684, <- 3
  '389078110571724801': 101750, <- 4
  '593157035499978752': 66255 } <- 5

For example obj['411510958020624384'] will give you 0, obj['560134275538747403'] will give you 3, and...

How can I do that? ~and thx.

1 Answers1

2

You can't do that. Object keys are unordered.

Support was more or less fixed in ECMAScript 2015, but it's still unreliable. It's far, far better to use an array that you sort, or an array of objects like below:

const keys = [{'411510958020624384':272216},{'482286641982078977':195951},{'469176984086380574':156025},{'560134275538747403':126684},{'389078110571724801':101750},{'593157035499978752':66255}];

const getIndex = (arr, key) => keys.findIndex(({ [key]: k }) => k);

console.log(getIndex(keys, "411510958020624384"));
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79