如何按自定义顺序(spring、summer、fall、winter)对JavaScript对象的键进行排序
Got it, let’s figure out how to reorder your inventory object’s keys to follow that specific spring → summer → fall → winter sequence. Here’s a straightforward, reliable way to do it:
The Core Idea
JavaScript objects (as of ES6+) do preserve key insertion order, but they don’t let you reorder existing keys directly. So we’ll create a new object, explicitly adding keys in your desired custom order by pulling values from the original inventory.
Step-by-Step Implementation
First, define your target order as an array—this acts as our "blueprint" for sorting. Then we’ll use Object.fromEntries() to build a new object using that blueprint:
// Your original inventory object const inventory = { fall: { 'Category 1': [], 'Category 2': [] }, spring: { 'Category 1': [], 'Category 3': [] }, winter: { 'Category 3': [], 'Category 4': [] }, summer: { 'Category 4': [], 'Category 5': [] } }; // Define your custom key order const customSeasonOrder = ['spring', 'summer', 'fall', 'winter']; // Build the sorted object const sortedInventory = Object.fromEntries( customSeasonOrder.map(season => [season, inventory[season]]) ); // Verify the result console.log(sortedInventory);
How It Works
customSeasonOrderis our guide—we loop through this array in the exact order we want the keys to appear.map()converts each season name in the array into a key-value pair ([season, inventory[season]]), pulling the corresponding value from the original object.Object.fromEntries()takes that array of key-value pairs and turns it into a new object, with keys in the order we specified.
Edge Case Note
If your original object ever has extra seasons not listed in customSeasonOrder, you can add those to the end by combining the custom order with the remaining keys. For example:
const extraSeasons = Object.keys(inventory).filter(season => !customSeasonOrder.includes(season)); const fullOrder = [...customSeasonOrder, ...extraSeasons]; const sortedInventory = Object.fromEntries(fullOrder.map(season => [season, inventory[season]]));
But since your current inventory only has the four seasons in your target order, this extra step isn’t necessary here.
内容的提问来源于stack exchange,提问作者zoltalar

