Sorting JSON objects by their values is weirdly difficult in JavaScript.
Object keys are unordered, so you have to convert to an array, sort, and rebuild. You also have to handle nested values and mixed data types.
Let's look at how to do it properly.
1. Sort and Keep as an Array
The most common approach is to use Object.entries() to get an array of [key, value] pairs, and then use .sort().
const data = { banana: 3, apple: 5, orange: 1 }; const sortedArray = Object.entries(data).sort((a, b) => a[1] - b[1]); console.log(sortedArray); // Output: [ ['orange', 1], ['banana', 3], ['apple', 5] ] If you are sorting strings alphabetically, you compare the string values instead of subtracting them.
const stringData = { b: "zebra", a: "apple", c: "mango" }; const sortedStrings = Object.entries(stringData).sort((a, b) => a[1].localeCompare(b[1])); 2. Sort and Convert Back to an Object
If you need the result to be an object again, you can use Object.fromEntries().
const sortedObject = Object.fromEntries( Object.entries(data).sort((a, b) => a[1] - b[1]) ); console.log(sortedObject); // Output: { orange: 1, banana: 3, apple: 5 } Note: While this works in modern JavaScript engines, the ECMAScript specification states that integer-like keys are always iterated first in ascending order, regardless of insertion order. If your keys are strings (like "apple", "banana"), the object will maintain the sorted insertion order.
3. Sorting Nested Objects
If the values you are sorting by are nested (e.g., data.apple.meta.score), you need to access the nested property in the sort function.
const nestedData = { item1: { score: 42 }, item2: { score: 10 }, item3: { score: 99 } }; const sortedNested = Object.entries(nestedData).sort( (a, b) => a[1].score - b[1].score ); Common Gotchas
- Case sensitivity: When sorting strings,
"Zebra"will come before"apple"because uppercase letters have lower character codes. Use.toLowerCase()or.localeCompare()to handle this. - Mutating the original:
.sort()mutates the array in place. SinceObject.entries()creates a new array, you aren't mutating the original object, but it's something to keep in mind.
The Visual Way
Writing scripts is fine if you're building an app, but if you just need to sort a complex JSON payload once, doing it by hand is slow.
If you want to sort JavaScript and JSON object properties by their primitive or nested values in ascending or descending order visually, I built a free JS Object Value Sorter.
100% client-side. Nothing uploaded.
How do you usually handle sorting complex objects in JavaScript? Let me know in the comments.
