-2

Hi I am beginning with javascript and I would like to sort this JSON Object by value:

aa = {Deuxième immatriculation: 2, Première immatriculation: 1, Suppression: 3}

in order to have this result

bb = {Première immatriculation: 1,Deuxième immatriculation: 2, ,Suppression: 3}

How can I do this ? Thank you

userHG
  • 567
  • 4
  • 29
  • 1
    Does this answer your question? [Sorting object property by values](https://stackoverflow.com/questions/1069666/sorting-object-property-by-values) Did you try google first? – jmargolisvt May 15 '20 at 18:08
  • 2
    Object keys are not guarenteed to be in any order. If you need to impose an order, us an array, and sort the keys. – Taplar May 15 '20 at 18:08
  • @jmargolisvt Of course but there is a subtelty in this example but thank you for your great help – userHG May 15 '20 at 18:15
  • @Taplar Thank you – userHG May 15 '20 at 18:15

1 Answers1

1

The basic simple answer is NO, because the ordering of object properties is non-standard in ECMAScript. You should never make assumptions about the order of elements in a JavaScript object. An Object is an unordered collection of properties. The answers below show you how to "use" sorted properties, using the help of arrays, but never actually alter the order of properties of objects themselves. So, no, it's not possible. Even if you build an object with presorted properties, it is not guaranteed that they will display in the same order in the future.

So the better way is make it an array then do the sorting and rebuild the object as shown below

let input = {
  Deuxième_immatriculation: 2,
  Première_immatriculation: 1,
  Suppression: 3
}


let sortable = [];
for (let property in input) {
  sortable.push([property, input[property]]);
}


sortable.sort((a, b) =>a[1] - b[1]);

let objSorted = {}
sortable.forEach(item => objSorted[item[0]] = item[1])

console.log(objSorted)
Learner
  • 8,379
  • 7
  • 44
  • 82