如何动态地在jquery中对对象数组进行排序

时间:2015-06-28 16:54:25

标签: php jquery sorting

我知道当你对两个对象,对象a和对象b进行排序时,sort方法有效,

array.sort(function(a, b){
    var a1= a.name, b1= b.name;
    if(a1== b1) return 0;
    return a1> b1? 1: -1;
});

然而我回应了我的服务器中的stdclass对象列表,这是一个很长的列表,因为我希望按照它们的对象属性对它们进行分类。 如果我的数据列表如下所示,

      array( 
           [7] => stdClass Object
            (
           [id] => 3
           [title] => Electrition
           [img] => 
           [description] => 
           [school] => 
           [location] => 1
           [url] => 
           [tablename] => 3
           [votes] => 0
           [name] => John Doe
           [NumJobsdone] => 4
               )

             [8] => stdClass Object
           (
            [id] => 2
            [title] => Electrition
            [img] => 
            [description] => 
            [school] => 
            [location] => 1
            [url] => 
            [tablename] => 2
            [votes] => 0
            [name] => Tico Marinez
            [NumJobsdone] => 6
            )

            [9] => stdClass Object
            (
            [id] => 2
            [title] => Engineer
            [img] => 
            [description] => 
            [school] => 
            [location] => 1
            [tablename] => 2
            [votes] => 0
            [name] => Jerry Smity
            [NumJobsdone] => 6
           )

         [10] => stdClass Object
           (
           [id] => 2
           [title] => Engineer
           [img] => 
           [description] => 
           [school] => 
           [location] => 1
           [url] => 
           [tablename] => 2
           [votes] => 0
            [name] => Laura Bastian
           [NumJobsdone] => 6
             )
            ) 

我尝试按标题属性对它们进行排序,并且我使用$ .each方法迭代列表但是如何使用jquery动态地对多个对象进行排序?

1 个答案:

答案 0 :(得分:0)

尝试在return a.title > b.title比较功能

中使用.sort()

var arr = [{
  "title": "Electrician"
}, {
  "title": "Engineer"
}, {
  "title": "Architect"
}];

var res = arr.sort(function(a, b) {
  return a.title > b.title
});

document.getElementsByTagName("pre")[0].textContent = JSON.stringify(res, null, 2);
<pre></pre>

相关问题