Mark As Completed Discussion

Object Methods and Operations

Similar to arrays and strings in JavaScript, dictionaries also have built-in functions and properties for insertion, deletion, updating elements, and other operations that need to be performed on objects.

To get the total length of the dictionary, there is no method available in JavaScript. There are several methods to obtain this, one of which is to use the method Object.keys() which returns an array of keys in an object, and access its length.

JAVASCRIPT
1var student = {"ID": "01", "name":"Patrick", "age":18, "major":"Biology"}
2var length = Object.keys(student).length
3
4console.log(length)

To add new items in an object, there is no built-in method. Rather, they are directly assigned by specifying the key name and its value in bracket or dot notation as shown in the code block below.

JAVASCRIPT
1var student = {"ID": "01", "name":"Patrick", "age":18, "major":"Biology"}
2
3student["section"] = "A"
4student.email = "patrick123@xyz.com"
5
6console.log(student) //prints the updated dictionary

Another important operation in objects is the removal of items. This is performed by using the delete keyword by specifying the key name of the key-value pair that needs to be removed using bracket or dot notation.

JAVASCRIPT
1student = {"ID": "01", "name":"Patrick", "age":18, "major":"Biology"}
2
3delete student["age"]
4delete student.major
5
6console.log(student) //prints the updated dictionary

Some more commonly used object methods are,

  • To get all the properties or key-value pairs from an object, Object.entries(<object-name>) is used. It returns the key-value pairs in the form of a nested array.
  • To get all the keys in an object, Object.keys(<object-name>) is used. This returns all the keys in the form of an array.
  • To get all the values that exist in an object, Object.values(<object-name>) is used. All the values are returned in the form of an array.