0
0
Javascriptprogramming~5 mins

Object entries in Javascript

Choose your learning style9 modes available
Introduction

Object entries help you see all the keys and values inside an object as pairs. This makes it easy to work with each part separately.

When you want to loop through all keys and values of an object.
When you need to convert an object into a list of pairs for easier processing.
When you want to filter or transform object data based on keys or values.
When you want to check or find specific key-value pairs inside an object.
Syntax
Javascript
const entriesArray = Object.entries(objectName);

This returns an array where each item is a two-element array: [key, value].

The keys are always strings, and values can be any type.

Examples
Shows a simple object with two keys. The output is an array of pairs.
Javascript
const user = { name: 'Alice', age: 25 };
const entries = Object.entries(user);
console.log(entries);
When the object is empty, the result is an empty array.
Javascript
const emptyObject = {};
console.log(Object.entries(emptyObject));
With one key-value pair, the result is an array with one pair inside.
Javascript
const singleEntry = { city: 'Paris' };
console.log(Object.entries(singleEntry));
Values can be different types like numbers, booleans, or null.
Javascript
const mixedTypes = { id: 101, active: true, data: null };
console.log(Object.entries(mixedTypes));
Sample Program

This program shows an object with product details. It prints the object, then prints the entries array, and finally loops through each key-value pair to print them separately.

Javascript
const product = {
  name: 'Laptop',
  price: 1200,
  inStock: true
};

console.log('Before using Object.entries:');
console.log(product);

const productEntries = Object.entries(product);

console.log('\nAfter using Object.entries:');
console.log(productEntries);

// Loop through entries and print key and value
for (const [key, value] of productEntries) {
  console.log(`Key: ${key}, Value: ${value}`);
}
OutputSuccess
Important Notes

Time complexity is O(n) where n is the number of keys, because it reads all keys and values.

Space complexity is also O(n) because it creates a new array with all entries.

A common mistake is to expect Object.entries to return an object, but it returns an array of arrays.

Use Object.entries when you want to work with keys and values together, especially for loops or transformations.

Summary

Object.entries converts an object into an array of [key, value] pairs.

This helps you loop through or manipulate object data easily.

Remember it returns an array, not an object.