Home > Web Front-end > JS Tutorial > How to Loop and Access Properties in Arrays of Objects in JavaScript?

How to Loop and Access Properties in Arrays of Objects in JavaScript?

Mary-Kate Olsen
Release: 2024-11-10 11:33:02
Original
581 people have browsed it

How to Loop and Access Properties in Arrays of Objects in JavaScript?

Looping and Accessing Properties in Arrays of Objects

In JavaScript, looping through an array containing objects requires a modified approach compared to simple value arrays.

Iterating Over the Objects

To iterate over the objects in an array, you can use the forEach() method. Unlike the basic loop structure, forEach() executes a callback function for each element in the array:

myArray.forEach((element) => {
  console.log(element);
});
Copy after login

This code will log each object in the myArray array.

Accessing Object Properties

To access object properties within the loop, you can use dot notation or bracket notation:

forEach((element) => {
  console.log(element.x); // Dot notation
  console.log(element["y"]); // Bracket notation
});
Copy after login

Example

Let's modify the code in your question to use forEach():

for (var j = 0; j < myArray.length; j++) {
  console.log(myArray[j].x); // This returns "undefined"
}

myArray.forEach((element) => {
  console.log(element.x); // This works
});
Copy after login

In the first loop, it incorrectly tries to access the "x" property of the string "undefined." Using forEach() with an appropriate callback function allows you to successfully access and manipulate the properties of each object in the array.

The above is the detailed content of How to Loop and Access Properties in Arrays of Objects in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template