print dictionary js

How to Print Dictionary in JavaScript

Introduction

A dictionary is a data structure in JavaScript that stores data in key-value pairs. Each key is unique and maps to a specific value. In order to print the dictionary, we need to loop through the keys and values and display them on the screen.

Method 1: Using a for...in loop

To print the dictionary using a for...in loop, we first need to create an object that contains the key-value pairs. Then, we can loop through the object using the for...in loop and print out each key and value using the console.log() method.

let myDictionary = {
  "name": "Raju",
  "age": 25,
  "city": "New York"
};

for(let key in myDictionary) {
  console.log(key + ": " + myDictionary[key]);
}

Method 2: Using Object.entries()

The Object.entries() method returns an array of a given object's own enumerable property [key, value] pairs. We can use this method to print out the dictionary using a forEach() loop on the array.

let myDictionary = {
  "name": "Raju",
  "age": 25,
  "city": "New York"
};

Object.entries(myDictionary).forEach(([key, value]) => {
  console.log(`${key}: ${value}`);
});

Method 3: Using JSON.stringify()

The JSON.stringify() method converts a JavaScript object into a JSON string. We can use this method to convert the dictionary object into a JSON string and then print it out using the console.log() method.

let myDictionary = {
  "name": "Raju",
  "age": 25,
  "city": "New York"
};

console.log(JSON.stringify(myDictionary));

Output

  • name: Raju
  • age: 25
  • city: New York

These are the three methods to print dictionary in JavaScript. You can choose any of the above methods that suit your needs best.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe