javascript 如何遍历包含对象的数组并访问它们的属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16626735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to loop through an array containing objects and access their properties
提问by FlyingLizard
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?
无论如何,这是下一个问题。我如何使用循环访问,例如数组中的 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". How do I access these properties in the loop?
这将返回“未定义”。循环外的控制台日志再次告诉我对象都具有“x”的值。如何在循环中访问这些属性?
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!
谢谢!
回答by Dory Zidon
Use forEach its a built-in array function. Array.forEach()
:
使用 forEach 它是一个内置的数组函数。Array.forEach()
:
yourArray.forEach(function (arrayItem) {
var x = arrayItem.prop1 + 2;
console.log(x);
});
回答by Yuci
Some use cases of looping through an array in the functional programming wayin 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
参考
回答by Dwayne Charrington
You can use a for..of loopto 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. 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.
关于for..of
循环的最好的事情之一是它们可以迭代的不仅仅是数组。您可以迭代任何类型的可迭代对象,包括地图和对象。如果您需要支持旧浏览器,请确保使用转译器或类似 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. Furthermore, one of the coolest things is they also work with async/await as well.
我for..of
在 Javascript 中所做的几乎每一种迭代都使用循环。此外,最酷的事情之一是它们也可以与 async/await 一起使用。
回答by Thierry
for (var j = 0; j < myArray.length; j++){
console.log(myArray[j].x);
}
回答by Puyi Severino
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])
}
}
回答by MangoPapa7
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>");
}
}
回答by Vivek Sadh
myArray[j.x]
is logically incorrect.
myArray[j.x]
逻辑上不正确。
Use (myArray[j].x);
instead
使用(myArray[j].x);
替代
for (var j = 0; j < myArray.length; j++){
console.log(myArray[j].x);
}
回答by julien bouteloup
It's really simple using the forEach method since ES5+. You can directly change each property of each object in your array.
从 ES5+ 开始,使用 forEach 方法真的很简单。您可以直接更改数组中每个对象的每个属性。
myArray.forEach(function (arrayElem){
arrayElem = newPropertyValue;
});
If you want to access a specific property on each object:
如果要访问每个对象的特定属性:
myArray.forEach(function (arrayElem){
arrayElem.nameOfYourProperty = newPropertyValue;
});
回答by Partha Roy
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...
});
回答by sangamkumar91
This would work. Looping thorough array(yourArray) . Then loop through direct properties of each object (eachObj) .
这会奏效。循环彻底 array(yourArray) 。然后循环遍历每个对象 (eachObj) 的直接属性。
yourArray.forEach( function (eachObj){
for (var key in eachObj) {
if (eachObj.hasOwnProperty(key)){
console.log(key,eachObj[key]);
}
}
});