在Angular 6中按对象字段对对象数组进行排序

时间:2018-07-05 15:15:34

标签: javascript arrays angular typescript sorting

我正在从解析器获取一系列“产品”,这些解析器从json端点获取数据。

ngOnInit() {
  this.products = this._route.snapshot.data.products;
  console.log('products: ', this.products);
}

此数组中的一个对象的格式为

 {
    "id": 3645,
    "date": "2018-07-05T13:13:37",
    "date_gmt": "2018-07-05T13:13:37",
    "guid": {
        "rendered": ""
    },
    "modified": "2018-07-05T13:13:37",
    "modified_gmt": "2018-07-05T13:13:37",
    "slug": "vpwin",
    "status": "publish",
    "type": "matrix",
    "link": "",
    "title": {
        "rendered": "VPWIN"
    },
    "content": {
        "rendered": "",
        "protected": false
    },
    "featured_media": 0,
    "parent": 0,
    "template": "",
    "better_featured_image": null,
    "acf": {
        "domain": "SMB",
        "ds_rating": "3",
        "dt_rating": ""
    },
    ...
},

我想做的是按title.rendered字段对该数组进行排序

在过去,在AngularJS中,我只会在设置为此字段的模板中使用orderBy管道。显然,这已在Angular中删除,并且从研究中看来,首选的方法是对数据本身进行排序,例如在ngOnInit中。

但是我不知道如何按productsproducs.title.rendered进行排序。

3 个答案:

答案 0 :(得分:17)

您可以简单地使用Arrays.sort()

array.sort((a,b) => a.title.rendered.localeCompare(b.title.rendered));

工作示例:

var array = [{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"VPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""},},{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"adfPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""}},{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"bbfPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""}}];
array.sort((a,b) => a.title.rendered.localeCompare(b.title.rendered));
 
 console.log(array);

答案 1 :(得分:4)

尝试一下

products.sort(function (a, b) {
  return a.title.rendered - b.title.rendered;
});

OR

您可以导入lodash / underscore库,它具有许多可用于操纵,过滤,对数组进行排序等所有构建功能。

使用下划线:(下面仅是一个例子)

import * as _ from 'underscore';
let sortedArray = _.sortBy(array, 'title'); 

答案 2 :(得分:1)

未经测试,但应该可以工作

 products.sort((a,b)=>a.title.rendered > b.title.rendered)