-1

Okay, in my project im returned a json object like this:

  '18463685': {
    name: 'nidoranm',
    owner: '756135959145218128',
    level: 32,
    hpiv: 17,
    atkiv: 21,
    defiv: 16,
    spatkiv: 6,
    spdefiv: 10,
    speediv: 21,
    shiny: 'no',
    gender: 'male',
    totaliv: 91,
    uid: 18463685
  },
  '32075680': {
    name: 'golett',
    owner: '756135959145218128',
    level: 40,
    hpiv: 18,
    atkiv: 23,
    defiv: 7,
    spatkiv: 14,
    spdefiv: 12,
    speediv: 11,
    shiny: 'no',
    gender: 'unknown',
    totaliv: 85,
    uid: 32075680
  },
  '35339838': {
    name: 'exeggcute',
    owner: '756135959145218128',
    level: 20,
    hpiv: 13,
    atkiv: 13,
    defiv: 18,
    spatkiv: 11,
    spdefiv: 29,
    speediv: 5,
    shiny: 'no',
    gender: 'female',
    totaliv: 89,
    uid: 35339838
  },
  '35339838': {
    name: 'exeggcute',
    owner: '756135959145218128',
    level: 20,
    hpiv: 13,
    atkiv: 13,
    defiv: 18,
    spatkiv: 11,
    spdefiv: 29,
    speediv: 5,
    shiny: 'no',
    gender: 'female',
    totaliv: 89,
    uid: 35339838
  }
}

Each of these child objects within the parent object all share the same keys with different values, is there a way to sort the object based on something like its totaliv and be returned another object but with the child objects sorted based on value (descending)

My workspace is nodejs and im using javascript :)

djsnoob
  • 100
  • 6
  • Does this answer your question? [Sort JavaScript object by key](https://stackoverflow.com/questions/5467129/sort-javascript-object-by-key) – Thomas Sablik Feb 16 '21 at 18:39
  • @ThomasSablik Unfortunately not, im not trying to sort the object by keys but rather the value of one specific key thats in each object – djsnoob Feb 16 '21 at 18:41
  • But the answer is the same. It makes no sense to sort an object – Thomas Sablik Feb 16 '21 at 18:42

1 Answers1

2

You can use the sort function and then use the properties of each object

const sorted = Object.keys(obj).sort((a, b) => {
  return obj[a].totaliv - obj[b].totaliv;
});

Gets all of the keys of the object

Object.keys(obj)

Call the sort function on an array

.sort((a, b) =>

Compare objects to sort them by .totaliv

return obj[a].totaliv - obj[b].totaliv;

Sort Documentation

https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/array/sort

VtoCorleone
  • 14,341
  • 4
  • 33
  • 48