Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript

What is the Object.entries function in JavaScript?

Rukhshan Haroon

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The Object.entries function in JavaScript is used to extract the key-value pairs of an object.

Syntax

Object.entries(object_name)

Parameters

The Object.entries function takes 1 argument:

  • object_name - the name of the object whose key-value pairs will be extracted. This object must be predefined.

Return value

The Object.entries function returns all the key-value pairs in an object in the form of a nested array.

Example

The program below declares an object, which contains 3 key-value pairs. Each key is the territory’s name, and the corresponding value is the territory’s capital city.

The Object.entries function is called on this object, and the raw return value is printed using the console.log function.

Since the return value is a nested array, the array elements can be enumerated upon and printed iteratively using a for loop, as shown below:

// Declare a sample object with key-value pairs
const sample_object = {
America: 'New York',
Japan: 'Tokyo',
Australia: 'Sydney'
};
// Print the return value of Object.entries
console.log("Return value of Object.entries(sample_object):\n\n",Object.entries(sample_object))
// Enumerate over the return value and print it
console.log("\nThis return value is enumerable and can be accessed via a for loop:")
for ([territory, capital] of Object.entries(sample_object)) {
console.log(`${territory}: ${capital}`);
}

RELATED TAGS

javascript

CONTRIBUTOR

Rukhshan Haroon
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring