Difference between Object.keys() and Object.entries() methods in JavaScript
Object.keys() and Object.entries() are methods in JavaScript used to iterate over the properties of an object. They differ in how they provide access to object properties:
Object.keys() returns an array of a given object's own enumerable property names, while Object.entries() returns an array of a given object's own enumerable string-keyed property [key, value] pairs.
Table of Content
Object.keys()
Object.keys() iterates over an object's own enumerable properties, returning an array containing the keys of those properties.
Example: To demonstrate the implementation of the Object.Keys() method in JavaScript.
const obj = {
name: 'John',
age: 30,
city: 'New York'
};
const keys = Object.keys(obj);
console.log(keys);
Output
[ 'name', 'age', 'city' ]
Object.entries()
Object.entries() iterates over an object's own enumerable string-keyed property [key, value] pairs, returning an array of arrays.
Example: To demonstrate the implementation of the Object.entries() method in JavaScript.
const obj = {
name: 'John',
age: 30,
city: 'New York'
};
const entries = Object.entries(obj);
console.log(entries);
Output
[ [ 'name', 'John' ], [ 'age', 30 ], [ 'city', 'New York' ] ]
Difference between Object.keys() and Object.entries()
Features | Object.keys() | Object.entries() |
---|---|---|
Return Value | Array of object's keys | Array of [key, value] pairs |
Iteration Output | Returns keys as strings | Returns [key, value] pairs as arrays |
Use Case | Useful for iterating over keys | Useful for iterating over [key, value] pairs |
Example Output | `["name", "age", "city"]` | `[["name", "John"], ["age", 30], ["city", "New York"]]` |