javascript - 对象排序方法
PHP中文网
PHP中文网 2017-04-11 09:03:38
0
3
564
var data = {
  a: [
    {
      count: 0,
      str: 'this is a'
    }
  ],
  b: [
    {
      count: 1,
      str: 'this is b'
    }
  ]
}

排序后的结果为:

var data = {
  b: [
    {
      count: 1,
      str: 'this is b'
    }
  ],
  a: [
    {
      count: 0,
      str: 'this is a'
    }
  ]
}

有谁有较简单的方法吗

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(3)
小葫芦

用hashkey

洪涛

首先你这个data根本不是个对象数组...而是个对象
假如是个对象数组的话

function sortNumber(a, b){
    return a.count - b.count;
}
data.sort(sortNumber);
PHPzhong
          let nameArr = []

          for (let c in con) {
            nameArr.push({
              name: c,
              count: con[c][0].count
            })
          }

          const transform = function (obj) {
            let arr = []
            for (let item in obj) {
              arr.push(obj[item])
            }
            return arr
          }

          let objTransArr = transform(con)

          for (let d = 0; d < objTransArr.length; d++) {
            objTransArr[d].oldIndex = d
          }

          objTransArr.sort(function (x, y) {
            return x[0].count - y[0].count || x[0].oldIndex - y[0].oldIndex
          }).reverse()

          for (let f = 0; f < objTransArr.length; f++) {
            objTransArr[f].oldIndex = f
          }

          nameArr.sort(function (x, y) {
            return x.count - y.count || x.oldIndex - y.oldIndex
          }).reverse()

          let sourceObj = {}

          nameArr.forEach((item, index) => {
            sourceObj[item.name] = objTransArr[index]
          })
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template