-1

I have an array of objects as below:

"items"[
   {
      "0":{
         "name1":"max",
         "name2":"sam",
         "name3":"felicia",
         "age1":"10",
         "age2":"3",
         "age3":"20"
      }"1":{
         "name1":"lawrence",
         "name2":"faty",
         "name3":"kiki",
         "age1":"30",
         "age2":"23",
         "age3":"2"
      }
   }
]

I want to alphabetically sort name1, name2, name3 of each individual object.

Using below method sorts the objects but that is not what is wanted in this case

items.sort((a, b) => a.localeCompare(b));
  • 1
    If you need order, don't use a plain object. You should think of objects as *unordered* collections of key/value pairs. There *is* some order, but it depends on several factors, like insertion order, and whether the key represents an integer within a certain range. This can lead to very surprising results, so don't rely on it. For order use an array (of key/value pairs). – trincot May 12 '22 at 20:25
  • Unfortunately, I've been given this array of objects and am not allowed to change it. – anony2022 May 12 '22 at 20:31
  • Perhaps you mean you want `{name1: 'felicia', name2: 'max', name3: 'sam'}`? So name1 is always the first in alphabetic order? But this is a very odd data structure. – pilchard May 12 '22 at 20:31
  • 3
    Also, having keys with sequential numbers as suffixes (1, 2, 3, ...) is an anti-pattern. Also that is something that should be replaced with arrays. If this is some exercise in a course, I would have serious doubts about the quality of that course. – trincot May 12 '22 at 20:34
  • Does this answer your question? [Sort JavaScript object by key](https://stackoverflow.com/questions/5467129/sort-javascript-object-by-key) – programmerRaj May 12 '22 at 20:40
  • In your example code you try to sort the array, what you want to do is to sort the objects inside the array elements. The following code will to this. How to sort the object properties was answered here https://stackoverflow.com/questions/5467129/sort-javascript-object-by-key for (i in items) { for (j in items[i]) { items[0][1] = Object.keys(items[i][j]).sort().reduce( (obj, key) => { obj[key] = items[i][j][key]; return obj; }, {} ); } } – Falital May 12 '22 at 20:44

0 Answers0