[javascript] How to loop through an array containing objects and access their properties

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!

This question is related to javascript arrays iteration

The answer is


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);
 });

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]);
        }
    }
});

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... 
});

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

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

$.each(array, function(index, item) {
       console.log(index, item);
});

myArray[j.x] is logically incorrect.

Use (myArray[j].x); instead

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

_x000D_
_x000D_
var c = {_x000D_
    myProperty: [_x000D_
        { name: 'this' },_x000D_
        { name: 'can' },_x000D_
        { name: 'get' },_x000D_
        { name: 'crazy' }_x000D_
    ]_x000D_
};_x000D_
_x000D_
c.myProperty.forEach(function(myProperty_element) {_x000D_
    var x = myProperty_element.name;_x000D_
    console.log('the name of the member is : ' + x);_x000D_
})
_x000D_
_x000D_
_x000D_

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


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

_x000D_
_x000D_
var person = [];_x000D_
person[0] = {_x000D_
  firstName: "John",_x000D_
  lastName: "Doe",_x000D_
  age: 60_x000D_
};_x000D_
_x000D_
var i, item;_x000D_
_x000D_
for (i = 0; i < person.length; i++) {_x000D_
  for (item in person[i]) {_x000D_
    document.write(item + ": " + person[i][item] + "<br>");_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_


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

_x000D_
_x000D_
var students = [{_x000D_
    name: "Mike",_x000D_
    track: "track-a",_x000D_
    achievements: 23,_x000D_
    points: 400,_x000D_
  },_x000D_
  {_x000D_
    name: "james",_x000D_
    track: "track-a",_x000D_
    achievements: 2,_x000D_
    points: 21,_x000D_
  },_x000D_
]_x000D_
_x000D_
students.forEach(myFunction);_x000D_
_x000D_
function myFunction(item, index) {_x000D_
  for (var key in item) {_x000D_
    console.log(item[key])_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_


for (element in array) {
    console.log(array[element].property);
  }

This works.


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


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.


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.


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


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;
    });

_x000D_
_x000D_
const jobs = [_x000D_
    {_x000D_
        name: "sipher",_x000D_
        family: "sipherplus",_x000D_
        job: "Devops"_x000D_
    },_x000D_
    {_x000D_
        name: "john",_x000D_
        family: "Doe",_x000D_
        job: "Devops"_x000D_
    },_x000D_
    {_x000D_
        name: "jim",_x000D_
        family: "smith",_x000D_
        job: "Devops"_x000D_
    }_x000D_
];_x000D_
_x000D_
const txt = _x000D_
   ` <ul>_x000D_
        ${jobs.map(job => `<li>${job.name} ${job.family} -> ${job.job}</li>`).join('')}_x000D_
    </ul>`_x000D_
;_x000D_
_x000D_
document.body.innerHTML = txt;
_x000D_
_x000D_
_x000D_

Be careful about the back Ticks (`)


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to iteration

Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply? How to loop over grouped Pandas dataframe? How to iterate through a list of dictionaries in Jinja template? How to iterate through an ArrayList of Objects of ArrayList of Objects? Ways to iterate over a list in Java Python list iterator behavior and next(iterator) How to loop through an array containing objects and access their properties recursion versus iteration What is the perfect counterpart in Python for "while not EOF" How to iterate over a JavaScript object?