gotchajavascriptModerate
Object.keys() returns strings even for numeric keys
Viewed 0 times
Object.keysstring keysnumeric keysMap vs Objectkey types
Problem
Object.keys() always returns an array of strings, even when the object has numeric keys. const obj = {1: 'a', 2: 'b'}; Object.keys(obj) returns ['1', '2'] not [1, 2]. This causes comparison bugs.
Solution
Convert keys to numbers if needed, or use Map for numeric keys:
// Convert to numbers
const numKeys = Object.keys(obj).map(Number);
// Use Map for proper key types
const map = new Map();
map.set(1, 'a');
map.set(2, 'b');
[...map.keys()] // [1, 2] — actual numbers
// For iteration with numeric keys
for (const [key, value] of Object.entries(obj)) {
const numKey = Number(key);
// use numKey
}
// Convert to numbers
const numKeys = Object.keys(obj).map(Number);
// Use Map for proper key types
const map = new Map();
map.set(1, 'a');
map.set(2, 'b');
[...map.keys()] // [1, 2] — actual numbers
// For iteration with numeric keys
for (const [key, value] of Object.entries(obj)) {
const numKey = Number(key);
// use numKey
}
Why
JavaScript object keys are always strings (or Symbols). When you write {1: 'a'}, the key 1 is coerced to the string '1'. This is a fundamental language design choice. Map preserves key types.
Gotchas
- for...in also yields string keys
- JSON.parse preserves numeric keys as strings
- Map is the correct data structure when key types matter
- Object.keys order: integer-like keys sorted numerically first, then string keys in insertion order
Code Snippets
Object keys are always strings
const obj = { 1: 'a', 2: 'b', foo: 'c' };
Object.keys(obj) // ['1', '2', 'foo'] — all strings
// Use Map for typed keys
const m = new Map([[1, 'a'], [2, 'b']]);
[...m.keys()] // [1, 2] — actual numbersContext
When working with objects that have numeric keys
Revisions (0)
No revisions yet.