按属性对对象数组进行排序 [英] Sorting array of objects by property

查看:46
本文介绍了按属性对对象数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有来自数据库的这个集合:

I have this collection from DataBase:

var items = [{ 'Name':'Michael', 'TypeId':1 }
        { 'Name':'Max', 'TypeId':1 }
        { 'Name':'Andre', 'TypeId':1 }
        { 'Name':'Georg', 'TypeId':2 }
        { 'Name':'Greg', 'TypeId':3 }
        { 'Name':'Mitchell', 'TypeId':2 }
        { 'Name':'Ptro', 'TypeId':1 }
        { 'Name':'Helga', 'TypeId':1 }
        { 'Name':'Seruin', 'TypeId':2 }
        { 'Name':'Ann', 'TypeId':3 }
        { 'Name':'Marta', 'TypeId':2 }]

我需要按 TypeId 递增对这些项目进行排序.

I need to sort this items by TypeId increasing.

像这样:

var itemsSorted = [{ 'Name':'Michael', 'TypeId':1 }
        { 'Name':'Max', 'TypeId':1 }
        { 'Name':'Andre', 'TypeId':1 }
        { 'Name':'Ptro', 'TypeId':1 }
        { 'Name':'Helga', 'TypeId':1 }
        { 'Name':'Georg', 'TypeId':2 }
        { 'Name':'Mitchell', 'TypeId':2 }
        { 'Name':'Marta', 'TypeId':2 }]
        { 'Name':'Seruin', 'TypeId':2 }
        { 'Name':'Greg', 'TypeId':3 }
        { 'Name':'Ann', 'TypeId':3 }

JavaScript 中是否有任何内置函数可以按属性对对象数组进行排序?

Is there any built in function in JavaScript that can sort array of objects by property?

推荐答案

您可以使用 orderBy 过滤器.

You could use orderBy filter.

var itemsSorted  = $filter('orderBy')(items, 'TypeId')

正在查看

ng-repeat="item in items | orderBy: 'TypeId'"

默认过滤器是升序的(显式是 +TypeId),你可以使用 -TypeId 使其降序.

By default filters are ascending(explicit would be +TypeId), you could use -TypeId to make it descending.

其他内容

如果你想按多个属性排序,那么请使用数组而不是 string['TypeId', 'Name']

If you wanted to sort by multiple properties then do use array instead of string like ['TypeId', 'Name']

ng-repeat="item in items | orderBy: ['TypeId', 'Name']"

当您在控制器内部进行手动过滤时,您将获得巨大的性能优势.其中视图过滤较慢,因为它每次在摘要循环触发时评估 ng-repeat 表达和绑定.通常,您不会在小集合中看到任何性能下降,但在较大的集合中,您会发现视图过滤工作缓慢.

There is big performance benefit you get when you do manual filtering inside controller. where as filtering on view is slower as it evaluates ng-repeat express and bindings each time when digest cycle fire. Generally you won't see any performance hit in small collection, but in bigger collection you will see filtering on view will work slow.

这篇关于按属性对对象数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆