home ~ socials ~ other projects

Sort a JavaScript Object/Hash by Key

JavaScript

const data = {
  bravo: "This is Bravo",
  charlie: "This is Charlie",
  alfa: "This is Alfa",
  delta: "This is Delta",
}

const sorted = Object.entries(data).toSorted();

sorted.forEach(([key, value]) => {
  console.log(`${key}: ${value}`);
});
Output:
alfa: This is Alfa
bravo: This is Bravo
charlie: This is Charlie
delta: This is Delta

This approach uses .toSorted() this was part of Baseline 2023. It's listed as being available in all current major browsers as of press time.

-- end of line --

References