-2

I have a js object:

{
    "total_builds": 73,
    "history": {
        "2021-2-8": 4,
        "2021-2-5": 39,
        "2021-2-10": 6,
        "2021-2-6": 13,
        "2021-2-7": 14
    }
}

and how can i sort it like this:

{
    "total_builds": 73,
    "history": {
        "2021-2-5": 39,
        "2021-2-6": 13,
        "2021-2-7": 14,
        "2021-2-8": 4,
        "2021-2-10": 3
    }
}

Simply put how to sort a json object by key(date)?

graffitt
  • 7
  • 1
  • 1
    you're mistaking how objects work with arrays.. the correct answer is `objects dont get sorted` – The Bomb Squad Feb 10 '21 at 00:56
  • 1
    Non-array objects aren't meant to be sorted, they *usually* maintain key order but there's no guarantee of stability and no built-in sorting methods. How are you actually using the data? It would probably make more sense to sort it then. – John Montgomery Feb 10 '21 at 00:57
  • There are several problems with this. The first problem you're going to run into is that "history" is not a numeric sort; it is an alphabetic sort. So you're going to get 2021-2-1, 2021-2-10, 2021-2-2, etc. – Robert Harvey Feb 10 '21 at 00:57
  • 2
    Why do you want to sort an object? That doesn't really make sense to me. object are key value pared so sorting doesn't do anything. Also even if you did sort it that wouldn't do anything. – Colin Hale Feb 10 '21 at 00:57
  • 1
    Use a real date format, for example 2021-02-05 rather than an imaginary one such as 2021-2-5. – jarmod Feb 10 '21 at 01:00
  • Does this answer your question? [Sorting object property by values](https://stackoverflow.com/questions/1069666/sorting-object-property-by-values) – pilchard Feb 10 '21 at 01:48

1 Answers1

-1

You could transform history to array of key-value pairs, short that pairs, and transform back to object

const a = {
  total_builds: 73,
  history: {
    "2021-2-8": 4,
    "2021-2-5": 39,
    "2021-2-10": 6,
    "2021-2-6": 13,
    "2021-2-7": 14,
  },
};

a.history = Object.fromEntries(
  Object.entries(a.history).sort((a, b) => new Date(a[0]) - new Date(b[0]))
);

console.log(a);
hgb123
  • 13,869
  • 3
  • 20
  • 38