简体   繁体   English

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

[英]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?控制台应该会调出阵列中的每个 object,对吧? But in fact it only displays the first object.但实际上它只显示第一个 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?如何使用循环访问,例如数组中的 Object1.x?

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".循环外的控制台日志再次告诉我这些对象都有“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.有人建议我在其他地方为每个属性使用单独的 arrays,但我想确保我首先用尽了这条途径。

Thank you!谢谢!

Use forEach its a built-in array function.使用 forEach 它是一个内置的数组函数。 Array.forEach() : Array.forEach()

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

Some use cases of looping through an array in the functional programming way in JavaScript:在 JavaScript 中以函数式编程方式循环遍历数组的一些用例:

1. Just loop through an array 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
});

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.注意: Array.prototype.forEach() 严格来说不是函数式的,因为它作为输入参数的函数不应该返回值,因此不能被视为纯函数。

2. Check if any of the elements in an array pass a test 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

3. Transform to a new array 3.转换为新数组

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.注意:map() 方法使用对调用数组中的每个元素调用提供的函数的结果创建一个新数组。

4. Sum up a particular property, and calculate its average 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

5. Create a new array based on the original but without modifying it 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]

6. Count the number of each category 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}

7. Retrieve a subset of an array based on particular criteria 7. 根据特定条件检索数组的子集

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.注意: filter() 方法创建一个新数组,其中包含通过所提供函数实现的测试的所有元素。

8. Sort an array 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);

在此处输入图片说明

9. Find an element in an array 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);

在此处输入图片说明

The Array.prototype.find() method returns the value of the first element in the array that satisfies the provided testing function. Array.prototype.find() 方法返回数组中满足提供的测试函数的第一个元素的值。

References参考

You can use a for..of loop to loop over an array of objects.您可以使用for..of 循环遍历对象数组。

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. for..of循环最好的事情for..of是它们可以迭代的不仅仅是数组。 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.如果您需要支持旧浏览器,请确保使用转译器或类似 TypeScript 的东西。

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.我在 Javascript 中进行的几乎所有类型的迭代都使用for..of循环。 Furthermore, one of the coolest things is they also work with async/await as well.此外,最酷的事情之一是它们也可以与 async/await 一起使用。

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

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

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

myArray[jx] is logically incorrect. myArray[jx]在逻辑上是不正确的。

Use (myArray[j].x);使用(myArray[j].x); instead反而

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

It's really simple using the forEach method since ES5+.从 ES5+ 开始,使用 forEach 方法真的很简单。 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;
    });

This would work.这会奏效。 Looping thorough array(yourArray) .循环彻底 array(yourArray) 。 Then loop through direct properties of each object (eachObj) .然后循环遍历每个对象 (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).这是遍历对象数组的另一种方法(您需要在文档中包含 jQuery 库以用于这些对象)。

$.each(array, function(element) {
  // do some operations with each element... 
});

Array object iteration, using jQuery, (use the second parameter to print the string).数组对象迭代,使用jQuery,(使用第二个参数打印字符串)。

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

Accepted answer uses normal function.接受的答案使用正常功能。 So posting the same code with slight modification using arrow function on forEach因此,在 forEach 上使用箭头函数稍微修改后发布相同的代码

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

Also in $.each you can use arrow function like below同样在 $.each 中,您可以使用如下箭头函数

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

 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 (`)小心后面的勾号 (`)

 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.这是我如何能够实现它的方式之一。

This might help somebody.这可能会帮助某人。 Maybe it's a bug in Node.可能是 Node.js 的一个 bug。

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.我猜这里有某种内部优化破坏了 Node.js。

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

Error says the array is undefined, but it's not :-/ Node v11.15.0错误表示数组未定义,但不是:-/ Node v11.15.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.节点 JS 和 MySQL。

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

This works.这有效。

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

I want to loop and deconstruction assignment at the same time, so code like this: config.map(({ text, callback })=>add_btn({ text, callback }))我想同时循环和解构赋值,所以代码如下: config.map(({ text, callback })=>add_btn({ text, callback }))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何遍历包含对象对象的数组 - How to loop through an array containing objects of objects 如何遍历包含对象的数组和 JS 中的对象数组 - How to loop through array containing objects and array of objects in JS 如何遍历对象数组并访问每个数组内的属性以显示在 html 元素中? - how to loop through an array of objects and access the properties inside each array to display in an html element? 如何在React组件中遍历数组内部对象的属性? - How to loop through properties of objects inside of an array within a React component? 如何在 react/javascript For-Loop & ForEach 中访问对象数组中的属性? - How to access properties in array of objects in react/javascript For-Loop & ForEach? 遍历数组中的对象,打印属性 - Loop through objects in array, print properties 如何访问对象属性数组? - How to Access an array of objects properties? 如何循环遍历对象数组并使用 typescript 创建仅具有某些属性的新对象数组并做出反应? - How to loop through array of objects and create a new array of objects with only certain properties using typescript and react? 遍历包含数组的JSON对象,该数组包含的对象包含包含etc的数组 - Loop through JSON object containing array containing objects containing arrays containing etc 如何遍历对象数组 - How to loop through an array of objects
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM