组件:
import { Component, OnInit } from '@angular/core';
import * as _ from "lodash";
import { AF } from '../angularfire.service';
@Component({
selector: 'app-record-chart',
templateUrl: './record-chart.component.html',
styleUrls: ['./record-chart.component.less']
})
export class RecordChartComponent implements OnInit {
currentUser = [];
userRecords = [];
topRecords = [];
topRecordLabels = [];
movements = [
"Back Squat",
"Bench Press",
"Clean",
"Clean & Jerk",
"Deadlift",
"Front Squat",
"Jerk",
"Power Clean",
"Power Snatch",
"Push Press",
"Snatch",
"Strict Press"
];
public barChartOptions:any = {
scaleShowVerticalLines: false,
responsive: true
};
public barChartLabels = this.topRecords[0];
public barChartType:string = 'bar';
public barChartLegend:boolean = true;
public barChartData:any[] = [
{data: [65, 59, 80, 81, 56, 55, 40], label: 'Series A'},
{data: [28, 48, 40, 19, 86, 27, 90], label: 'Series B'}
];
// events
public chartClicked(e:any):void {
console.log(e);
}
public chartHovered(e:any):void {
console.log(e);
}
constructor(private afService: AF) {
// Get current user details.
afService.getCurrentUserInfo().then(currentUserDetails => {
this.currentUser.push(currentUserDetails);
}).then(() => {
// Populate lifts array
for(let movement of this.movements) {
this.afService.getRecords(movement, this.currentUser[0].userID).subscribe((data) => {
var sortedArray = _.orderBy(data, ['weight']);
var sortedArray2 = _.uniqBy(sortedArray,'weight');
// console.log(sortedArray2);
this.userRecords.push(sortedArray);
var newRecords = sortedArray
.filter(function(record) {
return sortedArray.find(function(innerRecord) {
return innerRecord.name === record.name && innerRecord.weight > record.weight; }) === undefined;
});
for (let record of newRecords) {
this.topRecords.push(record);
}
});
}
}).then(() => {
// console.log(this.topRecords);
for (item in this.topRecords) {
this.topRecordLabels.push(item.movement);
}
console.log(this.topRecords);
})
}
ngOnInit() {
}
}
this.topRecords
数组输出:
如何遍历此数组中的每个对象并将所有移动值推送到自己的数组中?我以为我可以在for循环中使用this.topRecords[0]
单独访问它们,但它总是返回0
的长度。
这是我认为可行的:
for (item in this.topRecords) {
this.topRecordLabels.push(item.movement);
}
但它会进行0次迭代。我一直在想弄清楚如何访问和遍历这个数组的对象。
答案 0 :(得分:2)
您可以使用map运算符遍历数组,然后为您的字段返回另一个数组,如下所示:
this.topRecordLabels = this.topRecords.map((item)=> item.movement);
答案 1 :(得分:0)
请先删除此行:
public barChartLabels = this.topRecords[0];
这没有任何意义。
您需要阅读不同的b / w for in
和for of
用以下代码替换您的代码:
for (let item of this.topRecords) {
this.topRecordLabels.push(item.movement);
}
有关详细信息,请查看链接:
What is the difference between ( for... in ) and ( for... of ) in javascript?
答案 2 :(得分:0)
@echonax想出了这个:
this.topRecordLabels = this.topRecords.map((item)=> item.movement)