如何在 TypeScript 中对对象数组进行排序?
具体来说,根据一个特定属性对数组对象进行排序,在本例中为 nome
(“姓名”)或 cognome
(“姓氏”)?
/* Object Class*/
export class Test{
nome:String;
cognome:String;
}
/* Generic Component.ts*/
tests:Test[];
test1:Test;
test2:Test;
this.test1.nome='Andrea';
this.test2.nome='Marizo';
this.test1.cognome='Rossi';
this.test2.cognome='Verdi';
this.tests.push(this.test2);
this.tests.push(this.test1);
谢谢!
最佳答案
这取决于您要排序的内容。您在 JavaScript 中为 数组 提供了标准的排序 函数,并且您可以编写专用于您的对象的复杂条件。 f.e
var sortedArray: Test[] = unsortedArray.sort((obj1, obj2) => {
if (obj1.cognome > obj2.cognome) {
return 1;
}
if (obj1.cognome < obj2.cognome) {
return -1;
}
return 0;
});
关于angular - 在 typescript 中对一组对象进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43311121/