如何遍历包含对象的数组并访问其属性

Fly*_*ard 160 javascript arrays iteration

我想循环遍历数组中包含的对象并更改每个对象的属性.如果我这样做:

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

console.log(myArray[j]);

}
Run Code Online (Sandbox Code Playgroud)

控制台应该调出阵列中的每个对象,对吧?但实际上它只显示第一个对象.如果我控制台将数组记录在循环外部,那么所有对象都会出现,所以肯定会有更多.

无论如何,这是下一个问题.如何使用循环访问数组中的Object1.x?

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

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

}
Run Code Online (Sandbox Code Playgroud)

这将返回"未定义".循环外的控制台日志再次告诉我,对象都具有"x"的值.如何在循环中访问这些属性?

我被推荐到其他地方为每个属性使用单独的数组,但我想确保我已经用尽了这个大道.

谢谢!

Dor*_*don 287

使用forEach是一个内置的数组函数.Array.forEach():

yourArray.forEach(function (arrayItem) {
    var x = arrayItem.prop1 + 2;
    console.log(x);
});
Run Code Online (Sandbox Code Playgroud)

  • 我担心IE 9不支持"forEach".不要怪我!我的雇主的产品给予了支持! (3认同)
  • @DoryZidon:forEach 不支持中断或停止 - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach (3认同)
  • 注意:“forEach”是阻塞的,不支持“await”。“for...of”循环将支持。 (3认同)
  • 很高兴为您提供帮助。Javascript变得非常酷。再加上forEach变得更好,也更容易阅读复杂的循环。 (2认同)
  • 请注意,确实有一个数组很重要.如果你从`document.getElementsByClassName`那里得到`yourArray`那将是一个HTMLCollection,而不是一个数组.然后[这个问题](http://stackoverflow.com/questions/24266313/using-foreach-on-an-array-from-getelementsbyclassname-results-in-typeerror-und)可能会有所帮助. (2认同)

Yuc*_*uci 66

一些用例在JavaScript 中以函数编程方式循环遍历数组:

1.只需循环一个数组

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
});
Run Code Online (Sandbox Code Playgroud)

注意:严格来说,Array.prototype.forEach()不是一种功能方式,因为它作为输入参数所采用的函数不应该返回一个值,因此不能将其视为纯函数.

2.检查数组中的任何元素是否通过测试

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
Run Code Online (Sandbox Code Playgroud)

3.转换为新数组

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

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

注意:map()方法创建一个新数组,其结果是在调用数组中的每个元素上调用提供的函数.

4.总结一个特定的属性,并计算其平均值

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
Run Code Online (Sandbox Code Playgroud)

5.基于原始数组创建新数组,但不进行修改

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]
Run Code Online (Sandbox Code Playgroud)

6.计算每个类别的数量

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}
Run Code Online (Sandbox Code Playgroud)

7.根据特定条件检索数组的子集

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

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

注意:filter()方法创建一个新数组,其中包含通过所提供函数实现的测试的所有元素.

8.对数组进行排序

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);
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

9.在数组中查找元素

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);
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

Array.prototype.find()方法返回数组中第一个满足提供的测试函数的元素的值.

参考

  • 这是一个很棒的参考 - 这是这个问题的原创,还是您在其他地方托管了类似的内容? (2认同)

Dwa*_*ton 34

在ECMAScript 2015 aka ES6中,您可以使用for..of循环来遍历对象数组.

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

在发布此答案时,Internet Explorer几乎不存在支持,但通过使用像Traceur或Babel这样的转换器,您可以使用这样的新Javascript功能,而无需担心哪些浏览器支持什么.


Thi*_*rry 28

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


dev*_*mba 17

这是一个如何做到这一点的例子:)

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])
  }
}
Run Code Online (Sandbox Code Playgroud)


小智 7

循环遍历一组对象是一个非常基本的功能.这对我有用.

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>");
  }
}
Run Code Online (Sandbox Code Playgroud)


小智 7

this.data = [{name:"Rajiv", city:"Deoria"},{name:"Babbi", city:"Salempr"},{name:"Brijesh", city:"GKP"}];
for(const n of this.data) {
    console.log(n.name)
}
Run Code Online (Sandbox Code Playgroud)


Viv*_*adh 6

myArray[j.x] 在逻辑上是不正确的.

(myArray[j].x);改用

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


小智 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;
Run Code Online (Sandbox Code Playgroud)

注意后面的勾号(`)


jul*_*oup 5

从ES5 +开始,使用forEach方法非常简单。您可以直接更改数组中每个对象的每个属性。

myArray.forEach(function (arrayElem){ 
  arrayElem = newPropertyValue;
});
Run Code Online (Sandbox Code Playgroud)

如果要访问每个对象上的特定属性:

myArray.forEach(function (arrayElem){ 
      arrayElem.nameOfYourProperty = newPropertyValue;
    });
Run Code Online (Sandbox Code Playgroud)


小智 5

这会奏效。循环彻底 array(yourArray) 。然后循环遍历每个对象 (eachObj) 的直接属性。

yourArray.forEach( function (eachObj){
    for (var key in eachObj) {
        if (eachObj.hasOwnProperty(key)){
           console.log(key,eachObj[key]);
        }
    }
});
Run Code Online (Sandbox Code Playgroud)


Hem*_*ari 5

接受的答案使用正常功能。因此,在 forEach 上使用箭头函数发布相同的代码,稍加修改

  yourArray.forEach(arrayItem => {
      var x = arrayItem.prop1 + 2;
      console.log(x);
  });
Run Code Online (Sandbox Code Playgroud)

同样在 $.each 中,您可以使用箭头函数,如下所示

 $.each(array, (item, index) => {
       console.log(index, item);
 });
Run Code Online (Sandbox Code Playgroud)