340

I want to cycle through the objects contained in an array and change the properties of each one. If I do this:

for (var j = 0; j < myArray.length; j++){

console.log(myArray[j]);

}

The console should bring up every object in the array, right? But in fact it only displays the first object. if I console log the array outside of the loop, all the objects appear so there's definitely more in there.

Anyway, here's the next problem. How do I access, for example Object1.x in the array, using the loop?

for (var j = 0; j < myArray.length; j++){

console.log(myArray[j.x]);

}

This returns "undefined." Again the console log outside the loop tells me that the objects all have values for "x". How do I access these properties in the loop?

I was recommended elsewhere to use separate arrays for each of the properties, but I want to make sure I've exhausted this avenue first.

Thank you!

Foreever
  • 7,099
  • 8
  • 53
  • 55
FlyingLizard
  • 3,521
  • 4
  • 16
  • 10
  • 5
    Can you post a sample of your array? The first code snippet seems correct. – Sirko May 18 '13 at 16:52
  • 1
    `j` is a number. You defined it at the top of your loop. –  May 18 '13 at 16:55
  • 6
    Maybe `myArray` is not really just an array after all?? – techfoobar May 18 '13 at 16:57
  • we need more info on how myArray is constructed – bgusach May 18 '13 at 17:09
  • With all following answers and having an accepted answer no one explains why the problem occurs and how to resolve it with for loop. `#forEach` works. But the question was about for loop. – FreeLightman Feb 23 '18 at 11:58
  • 1
    The simple syntax error that caused the problem in the second part of the original question is called out in [this answer](https://stackoverflow.com/a/16626812/5003971) (`myArray[j.x]` should be `myArray[j].x`). A regular `for` loop works just fine, if the syntax is correct. – c32hedge Mar 23 '18 at 19:48
  • Does this answer your question? [For-each over an array in JavaScript](https://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript) – Michael Freidgeim Nov 22 '21 at 05:08

18 Answers18

493

Use forEach its a built-in array function. Array.forEach():

yourArray.forEach(function (arrayItem) {
    var x = arrayItem.prop1 + 2;
    console.log(x);
});
Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
Dory Zidon
  • 10,497
  • 2
  • 25
  • 39
  • 5
    @DoryZidon: forEach not support break or stop - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach – Ankur Loriya Jan 02 '16 at 08:02
  • 4
    Note that it is important that you really do have an array. If you got `yourArray` from something like `document.getElementsByClassName` that would be an HTMLCollection, not an array. Then [this question](http://stackoverflow.com/questions/24266313/using-foreach-on-an-array-from-getelementsbyclassname-results-in-typeerror-und) could be helpful. – J0ANMM May 04 '17 at 08:26
  • 3
    Note: `forEach` is blocking and doesn't support `await`.The `for...of` loop will. – PotatoFarmer Jan 17 '20 at 06:10
307

Some use cases of looping through an array in the functional programming way in JavaScript:

1. Just loop through an array

const myArray = [{x:100}, {x:200}, {x:300}];

myArray.forEach((element, index, array) => {
    console.log(element.x); // 100, 200, 300
    console.log(index); // 0, 1, 2
    console.log(array); // same myArray object 3 times
});

Note: Array.prototype.forEach() is not a functional way strictly speaking, as the function it takes as the input parameter is not supposed to return a value, which thus cannot be regarded as a pure function.

2. Check if any of the elements in an array pass a test

const people = [
    {name: 'John', age: 23}, 
    {name: 'Andrew', age: 3}, 
    {name: 'Peter', age: 8}, 
    {name: 'Hanna', age: 14}, 
    {name: 'Adam', age: 37}];

const anyAdult = people.some(person => person.age >= 18);
console.log(anyAdult); // true

3. Transform to a new array

const myArray = [{x:100}, {x:200}, {x:300}];

const newArray= myArray.map(element => element.x);
console.log(newArray); // [100, 200, 300]

Note: The map() method creates a new array with the results of calling a provided function on every element in the calling array.

4. Sum up a particular property, and calculate its average

const myArray = [{x:100}, {x:200}, {x:300}];

const sum = myArray.map(element => element.x).reduce((a, b) => a + b, 0);
console.log(sum); // 600 = 0 + 100 + 200 + 300

const average = sum / myArray.length;
console.log(average); // 200

5. Create a new array based on the original but without modifying it

const myArray = [{x:100}, {x:200}, {x:300}];

const newArray= myArray.map(element => {
    return {
        ...element,
        x: element.x * 2
    };
});

console.log(myArray); // [100, 200, 300]
console.log(newArray); // [200, 400, 600]

6. Count the number of each category

const people = [
    {name: 'John', group: 'A'}, 
    {name: 'Andrew', group: 'C'}, 
    {name: 'Peter', group: 'A'}, 
    {name: 'James', group: 'B'}, 
    {name: 'Hanna', group: 'A'}, 
    {name: 'Adam', group: 'B'}];

const groupInfo = people.reduce((groups, person) => {
    const {A = 0, B = 0, C = 0} = groups;
    if (person.group === 'A') {
        return {...groups, A: A + 1};
    } else if (person.group === 'B') {
        return {...groups, B: B + 1};
    } else {
        return {...groups, C: C + 1};
    }
}, {});

console.log(groupInfo); // {A: 3, C: 1, B: 2}

7. Retrieve a subset of an array based on particular criteria

const myArray = [{x:100}, {x:200}, {x:300}];

const newArray = myArray.filter(element => element.x > 250);
console.log(newArray); // [{x:300}] 

Note: The filter() method creates a new array with all elements that pass the test implemented by the provided function.

8. Sort an array

const people = [
  { name: "John", age: 21 },
  { name: "Peter", age: 31 },
  { name: "Andrew", age: 29 },
  { name: "Thomas", age: 25 }
];

let sortByAge = people.sort(function (p1, p2) {
  return p1.age - p2.age;
});

console.log(sortByAge);

enter image description here

9. Find an element in an array

const people = [ {name: "john", age:23},
                {name: "john", age:43},
                {name: "jim", age:101},
                {name: "bob", age:67} ];

const john = people.find(person => person.name === 'john');
console.log(john);

enter image description here

The Array.prototype.find() method returns the value of the first element in the array that satisfies the provided testing function.

References

Yuci
  • 27,235
  • 10
  • 114
  • 113
  • 2
    This is a fantastic reference - is this original to this question or do you have something like this hosted elsewhere? – Salvatore Jun 08 '18 at 23:34
  • hi, if I want to show all the name and then do comparison, do you know how to do it? – dipgirl Jul 27 '19 at 15:24
  • 1
    @dipgirl, is it something like below? ```const people = [ {name: "john", age:23}, {name: "john", age:43}, {name: "jim", age:101}, {name: "bob", age:67} ]; const sortByAge = people.map(p => { console.log(p.name) return p }).sort(function (p1, p2) { return p1.age - p2.age; }); console.log(sortByAge);``` – Yuci Jul 28 '19 at 21:20
98

You can use a for..of loop to loop over an array of objects.

for (let item of items) {
    console.log(item); // Will display contents of the object inside the array
}

One of the best things about for..of loops is that they can iterate over more than just arrays. You can iterate over any type of iterable, including maps and objects. Make sure you use a transpiler or something like TypeScript if you need to support older browsers.

If you wanted to iterate over a map, the syntax is largely the same as the above, except it handles both the key and value.

for (const [key, value] of items) {
  console.log(value);
}

I use for..of loops for pretty much every kind of iteration I do in Javascript. Furthermore, one of the coolest things is they also work with async/await as well.

Dwayne Charrington
  • 6,524
  • 7
  • 41
  • 63
  • I prefer this in `async` functions than using `await Promise.all(array.map(async (element) => {` with a separate `try catch`. A lot cleaner code. – xinthose Sep 30 '20 at 14:52
  • `For..of` loops are definitely the best. I believe it's something like 90% or so faster than a forEach loop. – user Aug 04 '21 at 16:22
32
for (var j = 0; j < myArray.length; j++){
  console.log(myArray[j].x);
}
Thierry
  • 5,133
  • 3
  • 25
  • 30
18

Here's an example on how you can do it :)

var students = [{
    name: "Mike",
    track: "track-a",
    achievements: 23,
    points: 400,
  },
  {
    name: "james",
    track: "track-a",
    achievements: 2,
    points: 21,
  },
]

students.forEach(myFunction);

function myFunction(item, index) {
  for (var key in item) {
    console.log(item[key])
  }
}
adiga
  • 34,372
  • 9
  • 61
  • 83
dev mamba
  • 676
  • 7
  • 10
  • how would you get the value of the `track` property for each element and assign it to a variable to use or interpolate in another part of code? – Chris22 Mar 12 '19 at 21:40
10

Looping through an array of objects is a pretty fundamental functionality. This is what works for me.

var person = [];
person[0] = {
  firstName: "John",
  lastName: "Doe",
  age: 60
};

var i, item;

for (i = 0; i < person.length; i++) {
  for (item in person[i]) {
    document.write(item + ": " + person[i][item] + "<br>");
  }
}
adiga
  • 34,372
  • 9
  • 61
  • 83
MangoPapa7
  • 109
  • 1
  • 10
7

It's really simple using the forEach method since ES5+. You can directly change each property of each object in your array.

myArray.forEach(function (arrayElem){ 
  arrayElem = newPropertyValue;
});

If you want to access a specific property on each object:

myArray.forEach(function (arrayElem){ 
      arrayElem.nameOfYourProperty = newPropertyValue;
    });
julien bouteloup
  • 3,022
  • 22
  • 16
6

myArray[j.x] is logically incorrect.

Use (myArray[j].x); instead

for (var j = 0; j < myArray.length; j++){
  console.log(myArray[j].x);
}
JDB
  • 25,172
  • 5
  • 72
  • 123
Vivek Sadh
  • 4,230
  • 3
  • 32
  • 49
6

const jobs = [
    {
        name: "sipher",
        family: "sipherplus",
        job: "Devops"
    },
    {
        name: "john",
        family: "Doe",
        job: "Devops"
    },
    {
        name: "jim",
        family: "smith",
        job: "Devops"
    }
];

const txt = 
   ` <ul>
        ${jobs.map(job => `<li>${job.name} ${job.family} -> ${job.job}</li>`).join('')}
    </ul>`
;

document.body.innerHTML = txt;

Be careful about the back Ticks (`)

adiga
  • 34,372
  • 9
  • 61
  • 83
sipher
  • 61
  • 1
  • 2
6
this.data = [{name:"Rajiv", city:"Deoria"},{name:"Babbi", city:"Salempr"},{name:"Brijesh", city:"GKP"}];
for(const n of this.data) {
    console.log(n.name)
}
rajiv patel
  • 319
  • 3
  • 4
5

This would work. Looping thorough array(yourArray) . Then loop through direct properties of each object (eachObj) .

yourArray.forEach( function (eachObj){
    for (var key in eachObj) {
        if (eachObj.hasOwnProperty(key)){
           console.log(key,eachObj[key]);
        }
    }
});
sangamkumar91
  • 51
  • 1
  • 2
5

Accepted answer uses normal function. So posting the same code with slight modification using arrow function on forEach

  yourArray.forEach(arrayItem => {
      var x = arrayItem.prop1 + 2;
      console.log(x);
  });

Also in $.each you can use arrow function like below

 $.each(array, (item, index) => {
       console.log(index, item);
 });
Hemadri Dasari
  • 32,666
  • 37
  • 119
  • 162
4

Here's another way of iterating through an array of objects (you need to include jQuery library in your document for these).

$.each(array, function(element) {
  // do some operations with each element... 
});
Matthew Morek
  • 2,826
  • 2
  • 17
  • 13
Partha Roy
  • 1,575
  • 15
  • 16
3

Array object iteration, using jQuery, (use the second parameter to print the string).

$.each(array, function(index, item) {
       console.log(index, item);
});
M S
  • 41
  • 3
3

var c = {
    myProperty: [
        { name: 'this' },
        { name: 'can' },
        { name: 'get' },
        { name: 'crazy' }
    ]
};

c.myProperty.forEach(function(myProperty_element) {
    var x = myProperty_element.name;
    console.log('the name of the member is : ' + x);
})

This is one of the ways how I was able to achieve it.

adiga
  • 34,372
  • 9
  • 61
  • 83
Gurunath Rao
  • 105
  • 1
  • 8
1

I want to loop and deconstruction assignment at the same time, so code like this: config.map(({ text, callback })=>add_btn({ text, callback }))

Youth overturn
  • 341
  • 5
  • 7
0

This might help somebody. Maybe it's a bug in Node.

var arr = [ { name: 'a' }, { name: 'b' }, { name: 'c' } ];
var c = 0;

This doesn't work:

while (arr[c].name) { c++; } // TypeError: Cannot read property 'name' of undefined

But this works...

while (arr[c]) { c++; } // Inside the loop arr[c].name works as expected.

This works too...

while ((arr[c]) && (arr[c].name)) { c++; }

BUT simply reversing the order does not work. I'm guessing there's some kind of internal optimization here that breaks Node.

while ((arr[c].name) && (arr[c])) { c++; }

Error says the array is undefined, but it's not :-/ Node v11.15.0

PJ Brunet
  • 3,615
  • 40
  • 37
0

I know it's been long but for anyone else encountering this issue, my problem is that I was looping through an array of arrays containing only one array. Like this:

// array snippet (returned from here)
} else {
   callback([results])
}

And I was using the array like this

for(const result of results){
   console.log(result.x)
}

As you can see, the array I wanted to iterate over was actually inside another array. removing the square brackets helped. Node JS and MySQL.

Joseph Sang
  • 310
  • 2
  • 9