Vue.js - how to sort and objects inside the array by particular property and render it with “v-for”

问题: I have an array with a few objects inside. Each object contains a few properties. I use vue.js v-for method to render it in the list. But I cannot render it in the spec...

问题:

I have an array with a few objects inside. Each object contains a few properties.

I use vue.js v-for method to render it in the list.

But I cannot render it in the specific order of the given property. I use this function to sort it ascending:

    evenNumbers: function () {
      return this.numbers.sort(function (a, b) { return a - b });
    }

It works fine with a simple array like [22, 1, 2, 3, 4, 5]. But it does not work for the objects like this:

      numbers2: [
      {
        name: 'Alan',
        age: 72
      }, 
      {
        name: 'Thomas',
        age: 32
      }, 
      {
        name: 'Thomas',
        age: 32
      }, 
      {
        name: 'Michal',
        age: 32
      },
    ]
  }

I want to sort them by the age in the ascending order.

At the end I want to render them inside the li for example only {{ age }} property.

Here is a snippet with my code: https://jsfiddle.net/marektchas/jyznx475/2/


回答1:

Since you now have complex objects, sorting by the object directly won't work as you expect (the operator runs some implicit conversions resulting in NaN for every comparison).

You must sort by the specific property, in this case, age. So:

    evenNumbers2: function () {
      return this.numbers2.sort(function (a, b) { return a.age - b.age });
    }

See updated fiddle.

  • 发表于 2019-03-28 01:07
  • 阅读 ( 186 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除