How to loop through an array containing objects an

2019-01-03 21:04发布

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!

12条回答
Anthone
2楼-- · 2019-01-03 21:26

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... 
});
查看更多
我想做一个坏孩纸
3楼-- · 2019-01-03 21:27

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])
  }
}
查看更多
手持菜刀,她持情操
4楼-- · 2019-01-03 21:29
for (var j = 0; j < myArray.length; j++){
  console.log(myArray[j].x);
}
查看更多
女痞
5楼-- · 2019-01-03 21:34

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, (index, item) => {
       console.log(index, item);
 });
查看更多
祖国的老花朵
6楼-- · 2019-01-03 21:36

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>");
    }
}
查看更多
爷、活的狠高调
7楼-- · 2019-01-03 21:38

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;
    });
查看更多
登录 后发表回答