JavaScript中如何获取对象最后一个键并移至键首位?
Got it, let's break this down. If you need to take the last key from a JavaScript object, shift it to the first position, and get the updated object, here are a couple of reliable ways to do it.
Method 1: Using Object Literals and Spread Operator (Simple & Clean)
This works great for most cases where your object has non-numeric keys (numeric keys get automatically sorted in objects, but we’ll cover that edge case later).
// Your original object const originalObj = { firstName: "John", lastName: "Doe", age: 30 }; // Step 1: Get all keys from the object const keys = Object.keys(originalObj); // Handle empty object case to avoid errors if (keys.length === 0) { console.log("Object is empty!"); } else { // Step 2: Extract the last key (pop removes it from the keys array) const lastKey = keys.pop(); // Step 3: Build the new object – last key first, then the rest const updatedObj = { [lastKey]: originalObj[lastKey], ...originalObj }; console.log(updatedObj); // Output: { age: 30, firstName: 'John', lastName: 'Doe' } }
Quick Note:
The spread operator (...originalObj) adds all remaining key-value pairs after the last key. Since we removed lastKey from the keys array, there’s no risk of overwriting (though object keys are unique anyway, so even if we didn’t remove it, the first occurrence in the object literal takes priority).
Method 2: Using Object.fromEntries (More Robust for Edge Cases)
If you need to handle numeric keys or want a more explicit approach, Object.fromEntries is a solid choice. This method builds the object from an array of key-value pairs, so you have full control over the order.
const originalObj = { 1: "one", 2: "two", 3: "three" }; const keys = Object.keys(originalObj); if (keys.length === 0) { console.log("Object is empty!"); } else { // Get the last key without modifying the original keys array const lastKey = keys[keys.length - 1]; // Filter out the last key to get the remaining ones const remainingKeys = keys.filter(key => key !== lastKey); // Create an array of entries: last key first, then the rest const newEntries = [ [lastKey, originalObj[lastKey]], ...remainingKeys.map(key => [key, originalObj[key]]) ]; // Convert entries array back to an object const updatedObj = Object.fromEntries(newEntries); console.log(updatedObj); // Output: { '3': 'three', '1': 'one', '2': 'two' } }
Why This Works:
Object.fromEntries respects the order of the entries array, so your last key will definitely be first. This is especially useful if your object has numeric keys, since Object.keys() sorts numeric keys in ascending order by default – this method preserves your desired order regardless.
Key Things to Keep in Mind:
- Object Key Order: In ES6+, objects preserve the insertion order of string and symbol keys. Numeric keys are sorted numerically, so keep that in mind if your object uses numeric keys.
- Empty Objects: Always add a check for empty objects to avoid errors when trying to access the last key.
Hope this solves your problem! Let me know if you have any specific edge cases to handle.
内容的提问来源于stack exchange,提问作者Frank Corona Prendes

