JavaScript Object.entries()

Share this article

In JavaScript, Object.entries() is a method that returns an array of a given object’s own enumerable property key-value pairs. Each key-value pair is returned as a separate array inside the main array, making it useful for iterating over properties in an object.

Example

const user = {
  name: 'Alice',
  age: 25,
  country: 'USA'
};

console.log(Object.entries(user));
// Output: [['name', 'Alice'], ['age', 25], ['country', 'USA']]

What it does

Object.entries() takes each property of the object (like name, age, and country) and creates an array where each element is another array containing the key and its value. This method is particularly handy for looping through an object’s properties using methods like for...of.

  • Key-Value pairs: Converts object properties into a list of arrays, where each sub-array holds a key and its corresponding value.
  • Useful for iteration: Makes it easier to work with objects in loops, as you can directly access keys and values.

Examples

Example 1: Iterating with for...of

const car = {
  make: 'Honda',
  model: 'Civic',
  year: 2022
};

for (const [key, value] of Object.entries(car)) {
  console.log(`${key}: ${value}`);
}
// Output:
// make: Honda
// model: Civic
// year: 2022

Here, Object.entries() converts the car object into an array of key-value pairs, allowing the for...of loop to iterate over each property, providing both the key and value in each iteration.

Example 2: Converting an object into a Map

const fruit = {
  name: 'Apple',
  color: 'Red',
  quantity: 10
};

const fruitMap = new Map(Object.entries(fruit));
console.log(fruitMap);
// Output: Map { 'name' => 'Apple', 'color' => 'Red', 'quantity' => 10 }

Using Object.entries(), you can convert an object into a Map, which allows for more advanced manipulation and access methods, such as using get() and set() on key-value pairs.

Example 3: Filtering properties

const scores = {
  math: 85,
  science: 92,
  history: 78
};

const highScores = Object.entries(scores).filter(([key, value]) => value > 80);
console.log(highScores);
// Output: [['math', 85], ['science', 92]]

Object.entries() helps in filtering an object’s properties based on certain conditions. Here, we use it to get subjects with scores greater than 80.

Example 4: Converting back to an object

const entries = [['brand', 'Nike'], ['type', 'Shoes'], ['size', 42]];
const product = Object.fromEntries(entries);
console.log(product);
// Output: { brand: 'Nike', type: 'Shoes', size: 42 }

While Object.entries() breaks an object into an array of key-value pairs, you can use Object.fromEntries() to convert it back into an object when needed.