加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 06:57:30 所属栏目:安全 来源:网络整理
导读:如何在TypeScript中对对象数组进行排序? 具体来说,在一个特定属性上对数组对象进行排序,在本例中为nome(“name”)或cognome(“surname”)? /* Object Class*/export class Test{ nome:String; cognome:String;}/* Generic Component.ts*/tests:Test[];test
如何在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;
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读