Sub topic 3
The Order Properties Come Back In
This chapter assumes you already know how to loop with Object.keys, Object.values, and Object.entries, and that you are comfortable with map and array destructuring.
The Order Properties Come Back In
Object.keys and Object.entries follow a fixed order. Integer-like keys come first, sorted in ascending numeric order. All other string keys follow in the order they were inserted. Every key comes back as a string, including the numeric ones.
const obj = { b: 'B', 2: 'two', a: 'A', 1: 'one' };
console.log(Object.keys(obj)); // ['1', '2', 'b', 'a']A common mistake is to expect 'b' first because it was written first. If insertion order matters for numeric-looking IDs, use a Map instead.
Building New Objects with Object.fromEntries
Object.fromEntries is the inverse of Object.entries. It turns [key, value] pairs back into an object. You can convert an object to entries, map over them, and rebuild it:
const prices = { apple: 1.2, pear: 0.8, plum: 2 };
const discounted = Object.fromEntries(
Object.entries(prices).map(([fruit, price]) => [fruit, price * 0.5])
);
console.log(discounted); // { apple: 0.6, pear: 0.4, plum: 1 }What Object.keys Skips: Symbols and Non-Enumerable Properties
Object.keys returns only own, enumerable, string-keyed properties. Use the methods below when you need more:
const id = Symbol('id');
const user = { name: 'Ada', [id]: 7 };
Object.defineProperty(user, 'secret', { value: 'x', enumerable: false });
console.log(Object.keys(user)); // ['name']
console.log(Object.getOwnPropertyNames(user)); // ['name', 'secret']
console.log(Reflect.ownKeys(user)); // ['name', 'secret', Symbol(id)]| Method | Non-enumerable | Symbols |
|---|---|---|
| `Object.keys` | No | No |
| `Object.getOwnPropertyNames` | Yes | No |
| `Reflect.ownKeys` | Yes | Yes |
Edge Cases: null, Arrays, Strings, and Primitives
console.log(Object.keys(['x', 'y'])); // ['0', '1']
console.log(Object.entries('hi')); // [['0', 'h'], ['1', 'i']]
console.log(Object.keys(42)); // []
try {
Object.keys(null);
} catch (err) {
console.log(err instanceof TypeError); // true
}Adding and Deleting Properties While Looping
Object.keys returns a snapshot array. Deleting properties inside the loop does not change which keys the loop visits, so this pattern is safe:
const settings = { theme: 'dark', font: null, size: 14, color: undefined };
for (const key of Object.keys(settings)) {
if (settings[key] == null) {
delete settings[key];
}
}
console.log(settings); // { theme: 'dark', size: 14 }The loop also won't visit keys you add during it. Build a new object with Object.fromEntries if you need those keys.
Exercise
What does Object.keys({ z: 1, 10: 2, y: 3, 3: 4 }) return?
Show answer
['3', '10', 'z', 'y']. Integer-like keys come first in ascending numeric order, then the string keys in insertion order, and every key is returned as a string.
Exercise
Write an expression that returns a copy of { a: 1, b: 2 } with every value doubled.
Show answer
Object.fromEntries(Object.entries({ a: 1, b: 2 }).map(([k, v]) => [k, v * 2])), which gives { a: 2, b: 4 }.