微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

angular – 在打字稿中对对象数组进行排序?

如何在TypeScript中对对象数组进行排序?

具体来说,在一个特定属性上对数组对象进行排序,在本例中为nome(“name”)或cognome(“surname”)?

/* 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中为Arrays提供标准排序功能,您可以编写专用于对象的复杂条件. 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;
});
@H_502_27@

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐