对象形式数组如何排序

先直接给上方法:

     sortByKey:function(arr,key){
        return arr.sort(function(a,b){
          var x = a[key];
          var y = b[key];
          return ((x<y) ? -1 : ((x>y) ? 1 : 0))
        })
      }  

    这里我是在vue项目中用到的 ,其实什么项目中都是可以这么用的

结构:

    <ul>
      <li v-for="kid in kids" >{{kid.name}}-{{kid.age}}</li>
    </ul>

  初始数据:

    data() {
      return {
        kids:[
          {
            name:"a",
            age:25
          },
          {
            name:"b",
            age:20
          },
          {
            name:"c",
            age:15
          },
          {
            name:"d",
            age:5
          }
        ]
      }
    },

  结果:

要求按年龄从小到大排序:

methods方法:

    methods:{
      sortByKey:function(arr,key){
        return arr.sort(function(a,b){
          var x = a[key];
          var y = b[key];
          return ((x<y) ? -1 : ((x>y) ? 1 : 0))
        })
      }
    }

  computed算法:

     newKids:function(){
        return this.sortByKey(this.kids,'age')
      }

  然后 注意要改掉循环中的主循环体是newKids,即:

    <ul>
      <li v-for="kid in newKids" >{{child.name}}-{{child.age}}</li>
    </ul>

  结果就是:

另:return a-b 可以决定升降序

function sort(a,b){
  return a-b  
}

  

原文地址:https://www.cnblogs.com/ly-qingqiu/p/10956063.html