乐闻世界logo
搜索文章和话题

How to sort JavaScript object by key

1个答案

1

In JavaScript, objects themselves do not support sorting because they are collections of key-value pairs where the keys are unordered. If you want to sort an object based on a specific key, the common approach is to convert the key-value pairs into an array and then sort the array. Here are the specific steps and examples:

Steps

  1. Extract key-value pairs: Use the Object.entries() method to convert the object into an array, where each element is an array containing the key and value.
  2. Sort the array: Use the sort() method on the array to sort it based on the desired key.
  3. Reconstruct the object (if needed): After sorting, if you need to convert the array back to an object, use the reduce() method to rebuild it.

Example

Suppose we have the following object and want to sort it in ascending order based on each employee's age:

javascript
const employees = { "John": { age: 25, position: "Developer" }, "Jane": { age: 29, position: "Designer" }, "Sam": { age: 22, position: "Intern" } }; // 1. Convert to array let entries = Object.entries(employees); // 2. Sort by age entries.sort((a, b) => a[1].age - b[1].age); // 3. Reconstruct object (if needed) const sortedEmployees = entries.reduce((obj, [key, value]) => { obj[key] = value; return obj; }, {}); console.log(sortedEmployees);

Output Result

json
{ "Sam": { "age": 22, "position": "Intern" }, "John": { "age": 25, "position": "Developer" }, "Jane": { "age": 29, "position": "Designer" } }

This example first converts the employees object into an array, sorts it based on age, and then converts the sorted array back to an object. This approach allows you to sort the object's contents according to specific rules and handle sorting logic flexibly.

2024年6月29日 12:07 回复

你的答案