JavaScript Object.entries(obj) method
The Object.entries(obj)
method in JavaScript is used to retrieve an array of a given object's own enumerable property [key, value]
pairs. This method is useful for iterating over the properties of an object when you need both the keys and their corresponding values.
Syntax:
Parameters:
obj
: The object whose own enumerable property[key, value]
pairs are to be returned.
Return Value:
- An array of arrays, where each inner array consists of two elements: the property key and the corresponding value. The order of the entries is the same as they would be iterated over in a
for...in
loop (excluding properties inherited from the object's prototype).
Key Features:
- Only Own Properties:
Object.entries()
returns only the object's own properties, not properties inherited through the prototype chain. - Enumerable Properties: Only properties that are enumerable are included in the returned array. Non-enumerable properties are ignored.
- Order: The order of entries follows the same rules as those for
for...in
loops:- Integer keys (like
1
,2
, etc.) are listed in ascending order. - String keys are listed in the order they were added.
- Symbol keys are listed in the order they were added.
- Integer keys (like
Example 1: Basic Usage
In this example, Object.entries()
retrieves the key-value pairs of the person
object and returns them as an array of arrays.
Example 2: Using with Loop
You can use the returned array to iterate over the object's properties:
In this example, Object.entries(car)
returns the entries of the car
object, and forEach
is used to log each key-value pair.
Example 3: Non-Enumerable Properties
In this example, nonEnumerable
is not included in the output because it is defined as a non-enumerable property.
Summary:
Object.entries(obj)
is a convenient method for obtaining an array of a given object's own enumerable property[key, value]
pairs.- It is particularly useful for scenarios where you need to access both keys and values together, making it easy to iterate through an object's properties in a structured way.
- Understanding this method is essential for working with objects in JavaScript, especially when you want to manipulate or display the object's key-value pairs effectively.