There are many ways to traverse an array of objects in JavaScript. The following are four common methods: for
loop, for...of
loop, forEach
method and map
method, while traversing, access the properties of the object to get the corresponding value.
-
Loop
for
:const objArray = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 3, name: 'Charlie' }, ]; for (let i = 0; i < objArray.length; i++) { const obj = objArray[i]; console.log(obj.id, obj.name); }
-
Loop
for...of
:const objArray = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 3, name: 'Charlie' }, ]; for (const obj of objArray) { console.log(obj.id, obj.name); }
-
Method
forEach
:const objArray = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 3, name: 'Charlie' }, ]; objArray.forEach((obj) => { console.log(obj.id, obj.name); });
-
Method
map
(usually used to create a new array, but can also be used to iterate):const objArray = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 3, name: 'Charlie' }, ]; objArray.map((obj) => { console.log(obj.id, obj.name); return obj; });
All of the above methods can realize the extraction of property values in the object while traversing the object array.