JavaScript How to Convert Object to Array Easily
Object.keys(obj) to get an array of keys, Object.values(obj) for values, or Object.entries(obj) for key-value pairs as arrays.Examples
How to Think About It
Algorithm
Code
const obj = {a: 1, b: 2}; const keysArray = Object.keys(obj); const valuesArray = Object.values(obj); const entriesArray = Object.entries(obj); console.log('Keys:', keysArray); console.log('Values:', valuesArray); console.log('Entries:', entriesArray);
Dry Run
Let's trace converting {a:1, b:2} to arrays using Object.keys(), Object.values(), and Object.entries().
Start with object
obj = {a:1, b:2}
Get keys array
Object.keys(obj) returns ['a', 'b']
Get values array
Object.values(obj) returns [1, 2]
Get entries array
Object.entries(obj) returns [['a', 1], ['b', 2]]
| Method | Result |
|---|---|
| Object.keys(obj) | ['a', 'b'] |
| Object.values(obj) | [1, 2] |
| Object.entries(obj) | [['a', 1], ['b', 2]] |
Why This Works
Step 1: Extract keys
Object.keys(obj) returns an array of all property names (keys) in the object.
Step 2: Extract values
Object.values(obj) returns an array of all property values in the same order as keys.
Step 3: Extract entries
Object.entries(obj) returns an array of arrays, each containing a key and its corresponding value.
Alternative Approaches
const obj = {a:1, b:2}; const arr = []; for (const key in obj) { if (obj.hasOwnProperty(key)) { arr.push([key, obj[key]]); } } console.log(arr);
const obj = {a:1, b:2}; const entries = Object.keys(obj).map(key => [key, obj[key]]); console.log(entries);
Complexity: O(n) time, O(n) space
Time Complexity
All methods iterate over each property once, so time grows linearly with the number of properties.
Space Complexity
New arrays are created to hold keys, values, or entries, so space also grows linearly.
Which Approach is Fastest?
Built-in methods like Object.keys(), Object.values(), and Object.entries() are optimized and usually faster than manual loops.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Object.keys() | O(n) | O(n) | Getting keys array quickly |
| Object.values() | O(n) | O(n) | Getting values array quickly |
| Object.entries() | O(n) | O(n) | Getting key-value pairs as arrays |
| for...in loop | O(n) | O(n) | Manual control, older environments |
| Object.keys() + map | O(n) | O(n) | Custom processing of keys before pairing |
Object.entries() when you need both keys and values as pairs in an array.Array.from() without extracting keys or values first.