简体   繁体   English

按属性对数组中的javascript对象进行排序(angularjs过滤器)

[英]Sorting javascript objects in array by properties (angularjs filter)

I'm trying to sort an array of javascript objects by their properties for an angularjs application. 我正在尝试按angularjs应用程序的属性对javascript对象数组进行排序。 I need to be able to sort by Numbers and Strings. 我需要能够按数字和字符串排序。

So far i have expanded the filter from Armin provided in this thread to sort numbers and strings (see code below). 到目前为止,我已经扩展了该线程中提供的Armin的筛选器,以对数字和字符串进行排序(请参见下面的代码)。

What i am still missing is the ability to give a nested property (like user.surname ) to the filter. 我仍然缺少的是将嵌套属性(如user.surname )赋予过滤器的功能。 It should be dynamic, so that i would be able to provide any depth of nested properties to it. 它应该是动态的,这样我就可以为其提供任何深度的嵌套属性。 Is there a way to do this? 有没有办法做到这一点?

Here's my filter code: 这是我的过滤器代码:

angular.module('app')
    .filter('orderObjectBy', function(){
        return function(input, filterBy) {
            if (!angular.isObject(input)) return input;

            var attribute = filterBy;
            var reverse = false;

            if (filterBy.substr(0,1) == '-') {
                attribute = filterBy.substr(1);
                reverse = true;
            }

            var array = [];
            for(var objectKey in input) {
                array.push(input[objectKey]);
            }

            if (parseInt(array[0][attribute])) {
                array.sort(function(a, b){
                    a = parseInt(a[attribute]);
                    b = parseInt(b[attribute]);
                    return a - b;
                });
            } else {
                array.sort(function (a,b) {
                    if (a[attribute] < b[attribute]) {
                        return -1;
                    } else if (a[attribute] > b[attribute]) {
                        return 1;
                    } else {
                        return 0;
                    }
                });
            }

            if (reverse) {
                return array.reverse();
            } else {
                return array;
            }

        }
    });

its pretty straight forward check this out: http://jsbin.com/duzurazo/2/edit 它很简单直接检查一下: http : //jsbin.com/duzurazo/2/edit

you can use something like 您可以使用类似

  <li ng-repeat="prop in props | orderBy:'order.v'"> {{prop.order.v}} </li>

where model is something like 那里的模型就像

  $scope.props = [{order:{v:"1"}},{order:{v:"5"}},{order:{v:"2"}}];

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

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