What is the Dict.set() function in Node.js?

Share

In this shot, we will discuss the Dict.set() function in Node.js. The Dict collection is available in the collections package. To install the collections package, you can execute the command below:

npm i collections
Install the collections module

The Dict.set() function is used to insert a key-value pair in the dictionary collection.

Terminal 1
Terminal
Loading...

Syntax

The syntax of the Dict.set() function is given below:

void set(K key, V value);
Syntax of the Dict.set() function in Node.js

Parameter

The Dict.set() function accepts two parameters:

  • Key: The value of the key that we want to insert in the dictionary collection.
  • Value: The value associated with the key above that needs to be inserted in the dictionary collection.

Return

The Dict.set() function returns a boolean value where true indicates the new key-value pair has been inserted successfully and false indicates that the key-value pair is not inserted.

Code

Let’s see how this function is used in the code.

var Dict = require("collections/dict");
var dictionary_obj = new Dict({'a': 1, 'b': 2});
console.log("Number of elements in Dictionary: ", dictionary_obj.length);
console.log("Elements in the Dictionary: ",dictionary_obj.toObject());
var is_element_inserted = dictionary_obj.set('c', 3);
is_element_inserted = dictionary_obj.set('d', 4);
console.log("Are the elements inserted?: ", is_element_inserted)
console.log("Number of elements in Dict: ", dictionary_obj.length);
console.log("Elements in the Dictionary: ", dictionary_obj.toObject());

Explanation

  • In line 1, we import the require package.
  • In line 3, we create an object of Dict collection and added two key-value pairs in the dictionary object.
  • In lines 5 and 6, we print the number of key-value pairs and the key-value pairs itself that are present in the dictionary object using the length and the toObject()method.
  • In lines 8 and 9, we call the set() function and pass the key-value pairs that needs to be inserted.
  • In line 10, we print the boolean value indicating whether the insertion was successful.
  • Finally, in lines 12 and 13, we print the number of elements and the elements that are present in the dictionary, after inserting the new key-value pairs.