循环遍历对象数组中的项
Looping through items in an array of objects
我有一个对象数组。
ABC.getAggregation("V")[0].getItems();
这就产生了这样的结果:
我的对象数组
在控制台中,我可以通过指定项目的位置来获得我想要的结果,如下所示:
ABC.getAggregation("V")[0].getItems()[0].getPosition()
ABC.getAggregation("V")[0].getItems()[1].getPosition()
ABC.getAggregation("V")[0].getItems()[2].getPosition()
上述代码的结果产生字符串值,例如"3.4554,43,0"。
如何循环遍历每个项目并在代码中获得位置。就像我在控制台中键入的上面的代码一样。不会总是有3个对象,这就是为什么我不能硬编码上面的3行。
尝试使用Array.prototype.forEach((函数。将为数组中的每个元素调用函数,并将元素作为第一个参数传入。
ABC.getAggregation("V")[0].getItems().forEach( function (item) {
item.getPosition();
//do something else
});
更多关于".forEach((">
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
您可以像对待任何其他数组一样对待它:
var myArray = ABC.getAggregation("V")[0].getItems();
for(var i=0; i< myArray.length; i++){
myArray[i].getPosition(); //Do something with the position.
}
您可以使用for循环遍历所有循环。
for(var i=0; i<ABC.getAggregation("V").getItems().length; i++) {
ABC.getAggregation("V")[0].getItems()[i].getPosition();
}
您可以使用forEach循环遍历所有循环。
ABC.getAggregation("V").getItems().forEach (item, index) {
return ABC.getAggregation("V")[0].getItems()[index].getPosition();
}
迭代数组中每个对象的一种非常简单的方法是在数组上使用for循环,您甚至不需要声明迭代变量。
例如:
var anArray = ['one', 'two', 'three'];
for( i in anArray){
console.log('index #: ' + i );
console.log(anArray[i]);
}
将打印出数组中的所有元素:
index #: 0
one
index #: 1
two
index #: 2
three
!!显然,这是一个很好的例子,说明了如何不这样做:P
你可以将项目分配给一个数组,并像这样循环:
var items = ABC.getAggregation("V")[0].getItems();
var returnString = "";
for (var key in items ) {
if (items .hasOwnProperty(key)) {
var element = items [key];
returnString += element.getPosition() + ',';
}
}
returnString = returnString.substring(0, x.length-1);
console.log(returnString);
相关文章:
- 循环遍历以数组为值的Javascript对象
- 如何遍历包含对象的数组-javascript
- JS.循环遍历多维数组,以计数元素在每列中的出现次数
- 根据PHP中数组的长度在Google Maps API中循环遍历标记
- 无法在javascript中循环遍历对象数组
- 如何使用jquery遍历具有动态添加元素的数组
- 我想遍历一个对象数组,我不想要任何重复项
- 如何遍历 JSON 对象以适合 JavaScript 数组
- 如何遍历 d3 中的值内部数组并添加相应的子元素
- Javascript 尝试遍历对象数组以显示其属性
- 使用jQuery循环遍历颜色数组
- javascript循环遍历列表项,并在数组中返回结果
- 循环遍历以数组作为值的对象的对象
- 遍历jQuery JSON对象数组
- 用javascript遍历映射中的数组
- 遍历嵌套的Javascript数组以创建路径
- 根据属性值创建多个对象数组,然后遍历每个数组
- 使用内部数组遍历数组并创建新对象 - AngularJS
- Jquery中的关联数组遍历每个元素
- Javascript - 使用数组遍历字段