The Object.entries
function in JavaScript is used to extract the key-value pairs of an object.
Object.entries(object_name)
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.The Object.entries
function returns all the key-value pairs in an object in the form of a nested array.
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 pairsconst sample_object = {America: 'New York',Japan: 'Tokyo',Australia: 'Sydney'};// Print the return value of Object.entriesconsole.log("Return value of Object.entries(sample_object):\n\n",Object.entries(sample_object))// Enumerate over the return value and print itconsole.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}`);}
Free Resources