我从数据库中获取一个数组(按降序排列),并将它们打印在表格和图表的前面,如图所示:
但是在图表的一部分中,我想按升序对其进行排序,然后执行以下操作:
export class PruebasComponent implements OnInit {
data: any[];
dataSource: PeriodicElement[] = [];
lineChartData: ChartDataSets[];
.......
ngOnInit() {
this.loading = true;
this.datos.getDesktopLimit().subscribe(
res => {
this.loading = false;
this.data = [res];
this.dataSource = this.data[0]; //aqui almaceno el arreglo y lo paso al componente html
this.barChartData = true;
this.getFilter(this.dataSource); // ejecuto la funcion getFilter()
}
)
}
通过排序,我按升序对其进行排序以将其传递给图表
getFilter(data) {
console.log(data);
data.sort((a, b) => a.id - b.id); //ordenar de forma ascendente para la grafica
for (let entry of data) {
this.date.push(moment(entry.created).format('DD-MM-YYYY HH:mm'))
this.time.push(entry.total_load_time * 0.001)
}
this.lineChartData = [{ data: this.time, label: 'Time Render' }];
this.lineChartLabels = this.date;
this.loading = false
}
确实它对我进行了排序,但表格也按升序排序
你有一个引用问题,在javascript(TS也是)中,所有对象都通过引用传递。您必须将两个对象分开:表格和图形。
然后:
现在,当您进行排序时,其他人不会自动更改,其想法是,当您将其传递给字符串然后再次传递给 JSON 时,您会丢失引用。
用 JSON.parse 做是最安全的,这取决于你的对象有多深(对象中的对象)。
制作对象副本并避免引用的其他方法是使用
Object.assign()
和传播运算符。...
后者消耗的资源更少,因为 JSON.parse 方法需要更多的 CPU,如果您要转换大型数组(>30k 记录),您会注意到这一点。
希望对你有帮助,问候!