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

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

问题描述

我从数据库中获得了这个集合:

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 过滤器.

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天全站免登陆