-1

I have an object {5:"James",1:"John", 3:"Jade"}. When reading its entries it should read it in below way {1:"john",3:"Jade",5:"James"}, without modifying the actual object.

Eddie
  • 26,593
  • 6
  • 36
  • 58
Asutosh
  • 1,775
  • 2
  • 15
  • 22
  • 2
    Did you try simply searching “sort object keys in JS”? Duplicate of [Sort JavaScript object by key](https://stackoverflow.com/questions/5467129/sort-javascript-object-by-key). – Sebastian Simon Jul 26 '20 at 06:24
  • Well, as your key are numeric in this case, when you create the same object on developer console, you will see it automaticaly enumrate them in proper order, but if the keys are string then result would have been different. Just try this out on console. let a = { 5: "James", 1: "John", 3: "Jade", 10: "ten", 7: "seven" }; console.log(a); – Saroj Jul 26 '20 at 06:41

1 Answers1

1

Just sort the object

const obj = {5:"James",1:"John", 3:"Jade"};

const result = Object.fromEntries( Object.keys(obj).sort().map((key) => {
  return [key, obj[key]];
}));

console.log(result);
Sivakumar Tadisetti
  • 4,865
  • 7
  • 34
  • 56