How to Get All Entries of Object in JavaScript Easily
Use
Object.entries(yourObject) to get an array of all key-value pairs from an object in JavaScript. Each entry is an array where the first element is the key and the second is the value.Syntax
The Object.entries() method takes an object and returns an array of its own enumerable string-keyed property [key, value] pairs.
Object.entries(obj): Returns an array of arrays, each containing a key and its corresponding value.
javascript
const obj = { a: 1, b: 2 }; const entries = Object.entries(obj); console.log(entries);
Output
[["a", 1], ["b", 2]]
Example
This example shows how to get all entries of an object and loop through them to print each key and value.
javascript
const person = { name: "Alice", age: 30, city: "Wonderland" }; const entries = Object.entries(person); for (const [key, value] of entries) { console.log(`${key}: ${value}`); }
Output
name: Alice
age: 30
city: Wonderland
Common Pitfalls
One common mistake is trying to use Object.entries() on null or undefined, which causes an error. Also, Object.entries() only includes an object's own enumerable properties, not inherited ones.
Wrong way example:
const obj = null; console.log(Object.entries(obj)); // Throws TypeError
Right way example:
const obj = { x: 1 };
if (obj !== null && obj !== undefined) {
console.log(Object.entries(obj));
}Quick Reference
Object.entries(obj) returns an array of [key, value] pairs from obj.
- Keys are strings.
- Only own enumerable properties are included.
- Useful for looping or converting objects.
Key Takeaways
Use Object.entries(obj) to get all key-value pairs as arrays.
Each entry is an array: [key, value].
Object.entries only includes own enumerable properties.
Avoid calling Object.entries on null or undefined.
Use for...of loop to iterate over entries easily.