简体   繁体   English

根据angular2中的一些json值对json数据进行排序

[英]Sort a json data based on a some json value in angular2

This is my json: 这是我的json:

{
   {
    "FirstName": "Adam" ,
    "Order": 3
   },
   {
    "FirstName": "Baron" ,
    "Order": 1
   },
   {
    "FirstName": "Ashton" ,
    "Order": 4
   },
   {
    "FirstName": "Kara" ,
    "Order": 2
   }
}

I want to order this based on "Order" value. 我想根据“订单”值订购此商品。 My hunt did not get me anything efficient. 我的狩猎没有使我有任何效率。

您可以使用管道, Sorting

*ngFor="let option of options | orderBy:'Order'"
var people = [
   {
    "FirstName": "Adam" ,
    "Order": 3
   },
   {
    "FirstName": "Baron" ,
    "Order": 1
   },
   {
    "FirstName": "Ashton" ,
    "Order": 4
   },
   {
    "FirstName": "Kara" ,
    "Order": 2
   }
];
function sortJSON(data, key) {
    return data.sort(function (a, b) {
        var x = a[key];
        var y = b[key];
        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
    });
}

var people2 = sortJSON(people, 'Order');
console.log("JSON",JSON.stringify(people2));

You could also do this with Lodash : 您也可以使用Lodash进行此操作

import * as _ from 'lodash';

_.sortBy(people, p => p.Order);

The advantage is that is also comes with a lot more functionality that can be very handy. 优点是还附带了很多非常方便的功能。 Just be mindful of what you import from it, so not to bloat your output bundle. 请注意从中导入的内容,不要膨胀输出包。

Don't use pipes for sorting. 不要使用管道进行排序。 Snippet from the Pipes documentation : Pipes文档中的片段:

Appendix: No FilterPipe or OrderByPipe 附录:无FilterPipe或OrderByPipe

Angular doesn't provide pipes for filtering or sorting lists. Angular不提供用于过滤或排序列表的管道。 Developers familiar with AngularJS know these as filter and orderBy. 熟悉AngularJS的开发人员将其称为filter和orderBy。 There are no equivalents in Angular. Angular中没有等效项。

This isn't an oversight. 这不是疏忽。 Angular doesn't offer such pipes because they perform poorly and prevent aggressive minification. Angular不提供此类管道,因为它们的性能不佳并阻止了主动缩小。 Both filter and orderBy require parameters that reference object properties. filter和orderBy都需要引用对象属性的参数。 Earlier in this page, you learned that such pipes must be impure and that Angular calls impure pipes in almost every change-detection cycle. 在此页面的前面,您了解到此类管道必须是不纯的,并且Angular在几乎每个变更检测周期中都调用不纯管道。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM