home ~ socials ~ other projects

Sort a JavaScript Object/Hash by Nested Value

JavaScript

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

const sorted = Object.entries(data)
  .toSorted((a,b) => a[1].content.localeCompare(b[1].content));

sorted.forEach(([key, value]) => {
  console.log(`${key}: ${JSON.stringify(value)}`);
});
Output:
alfa: {"content":"This is Alfa"}
bravo: {"content":"This is Bravo"}
charlie: {"content":"This is Charlie"}
delta: {"content":"This is Delta"}
-- end of line --

References