JavaScirpt Tutorial Index

JavaScript Tutorial Javascript Example Javascript comment Javascript Variable Javascript Data Types Javascript Operators Javascript If Else Javascript Switch Statement Javascript loop JavaScript Function Javascript Object JavaScript Arrays Javascript String Javascript Date Javascript Math Javascript Number Javascript Dialog Box Javascript Window Object Javascript Document Object Javascript Event Javascript Cookies Javascript getElementByID Javascript Forms Validation Javascript Email Validation Javascript Password Validation Javascript Re-Password Validation Javascript Page Redirect Javascript Print How to Print a Page Using JavaScript Textbox events in JavaScript How to find the largest number contained in a JavaScript Array?

Misc

JavaScript P5.js JavaScript Minify JavaScript redirect URL with parameters Javascript Redirect Button JavaScript Ternary Operator JavaScript radio button checked value JavaScript moment date difference Javascript input maxlength JavaScript focus on input Javascript Find Object In Array JavaScript dropdown onchange JavaScript Console log Multiple variables JavaScript Time Picker Demo JavaScript Image resize before upload Functional Programming in JavaScript JavaScript SetTimeout() JavaScript SetInterval() Callback and Callback Hell in JavaScript Array to String in JavaScript Synchronous and Asynchronous in JavaScript Compare two Arrays in JavaScript Encapsulation in JavaScript File Type Validation while Uploading Using JavaScript or jquery Convert ASCII Code to Character in JavaScript Count Character in string in JavaScript Get First Element of Array in JavaScript How to convert array to set in JavaScript How to get current date and time in JavaScript How to Remove Special Characters from a String in JavaScript Number Validation in JavaScript Remove Substring from String in JavaScript

Interview Questions

JavaScript Interview Questions JavaScript Beautifier Practice Javascript Online Object in JavaScript JavaScript Count HTML Interpreter Getters and Setters in JavaScript Throw New Error in JavaScript XOR in JavaScript Callbacks and Promises in JavaScript Atob in JavaScript Binary in JavaScript Palindrome Number in JavaScript How to Get First Character Of A String In JavaScript How to Get Image Data in JavaScript How to get URL in JavaScript JavaScript GroupBy Methods difference-between-var-let-and-const-keyword-in-javascript JavaScript Beautifier Iterating over Objects in Javascript Find the XOR of two numbers without using the XOR operator Method Chaining in JavaScript Role of Browser Object Model (BOM) in JavaScript Advanced JavaScript Interview Questions Filter() in JavaScript For Loop in JavaScript Google Maps JavaScript API Hide and Show Div in JavaScript How to Find Object Length in JavaScript Import vs. Require in JavaScript JavaScript Frontend Frameworks JavaScript Goto JavaScript Image Compression JavaScript Obfuscator JavaScript Pop() Method JavaScript replaceAll() JavaScript URL Encode JavaScript vs ReactJS JQuery Traversing Regular Expression for Name Validation in JavaScript Switch Statement in JavaScript

Iterating over Objects in Javascript

What is an Object?

An object in Javascript is an unordered group of variables and methods. They are represented as sets of paired keys and values. During execution, an object's attributes and methods can be added, changed, or eliminated.

Declaring and initializing an object:

The simplest syntax for declaring an object is Object literal. The properties of an object are initialized within the curly braces '{ }'. Each property is listed as a key-value pair, with a colon ':' between each pair.

Example:

const student = {

  name:  "David",

  roll_no:  54,

  cgpa:  8.7

};

The constructor function is another method of declaring an object. Constructor functions are normal functions that are executed with the 'new' keyword. Instances of the Object are created using the 'new' keyword. The ‘this’ keyword is used to declare properties and assign them values inside the constructor function.

Example:

function Student(name, rollno, cgpa) {

  this.name = name;

  this.rollno = rollno;

  this.cgpa = cgpa;

}

// Using the constructor function to create a new instance of Student.

const student1 = new Student("David", 19, 9.2);

const student2 = new Student("Emma", 23, 8.5);

Iterating over objects:

In contrast to an array, we cannot directly loop around an object. Several ways for iterating over properties of an object are listed below:

  1. Using the 'for-in' loop.
  2. Using the 'Object.entries()’ method.
  3. Using the 'Object.keys()’ method.
  4. Using the 'Object.values()’ method.

1. Using the 'for-in' loop:

An object's enumerable attributes can be iterated using the for-in loop. It iterates through the Object's keys, allowing access to the associated value through the key.

Example:

const student = {

  name:  "David",

  roll_no:  54,

  cgpa:  8.7

};

//Using for-in loop to iterate over an object

for (let key in student) {

  console.log(key + ": " + student[key]);

}

Output:

Iterating over Objects in Javascript

Every enumerable property of the Object, including those inherited properties, is iterated over by the for-in loop. The hasOwnProperty() function may be used to filter out inherited properties. The hasOwnProperty() function determines if the key provided is an object's property, removing inherited properties.

Example:

const student = {

  name:  "David",

  roll_no:  54,

  cgpa:  8.7

};

//Using for-in loop to iterate over Object

for (let key in student) {

  if (student.hasOwnProperty(key)) {

    console.log(key + ": " + student[key]);

  }

}

Output:

Iterating over Objects in Javascript

2. Using ‘Object.entries()’ method:

JavaScript's Object.entries() function enables retrieval of key-value pairs as arrays while iterating over an object's enumerable attributes. A collection of arrays is returned by the Object.entries() method. A key-value pair can be found in every inner array. The first element of an inner array is the property key, and the second element is the associated value.

Example:

const student = {

  name:  "David",

  roll_no:  54,

  cgpa:  8.7

};

//Using Object.entries() function to iterate over object

const elements = Object.entries(student);

console.log("The elements array:")

console.log(elements);

for (let i = 0; i < elements.length; i++) {

  const [key, value] = elements[i];

  console.log(key + ": " + value);

}

Output:

Iterating over Objects in Javascript

When used with the hasOwnProperty() function, Object.entries() will only iterate over an object's properties.

3. Using the 'Object.keys()’ method:

An array of an object's property keys can be obtained by iterating over the enumerable properties of an object using JavaScript's Object.keys() function. Using the Object.keys() method, an array of the Object's keys is returned. Only the Object's enumerable properties are returned by Object.keys(); no inherited properties are returned.

Example:

const student = {

  name:  "David",

  roll_no:  54,

  cgpa:  8.7

};

//Using Object.keys() function to iterate over object

const elements = Object.keys(student);

console.log("The array returned by Object.keys() method:");

console.log(elements);

for (let i = 0; i < elements.length; i++) {

  const ele = elements[i];

  console.log(ele + ": " + student[ele]);

}

Output:

Iterating over Objects in Javascript

4. Using ‘Object.values()’ method:

JavaScript's Object.values() function enables to loop through an object's enumerable properties and obtain an array of each property's values. An array is returned that contains all of the values of the Object. The Object's keys are returned as an array using the Object.keys() function. Only the Object's enumerable properties are returned by Object.values(); inherited properties are not included. This approach is quite helpful when you need to do actions based on the values, without the requirement for the matching keys.

Example:

const student = {

  name:  "David",

  roll_no:  54,

  cgpa:  8.7

};

//Using Object.values() function to iterate over object

const elements = Object.values(student);

console.log("The array returned by Object.values() method:");

console.log(elements);

for (let i = 0; i < elements.length; i++) {

  const ele = elements[i];

  console.log(ele);

}

Output:

Iterating over Objects in Javascript