如果我有一个JavaScript对象,如:

var list = {
  "you": 100, 
  "me": 75, 
  "foo": 116, 
  "bar": 15
};

是否有一种方法可以根据值对属性进行排序?最后得到

list = {
  "bar": 15, 
  "me": 75, 
  "you": 100, 
  "foo": 116
};

当前回答

a = { b: 1, p: 8, c: 2, g: 1 }
Object.keys(a)
  .sort((c,b) => {
    return a[b]-a[c]
  })
  .reduce((acc, cur) => {
    let o = {}
    o[cur] = a[cur]
    acc.push(o)
    return acc
   } , [])

输出= [{p: 8}, {c: 2}, {b: 1}, {g: 1}]

其他回答

let toSort = {a:2323, b: 14, c: 799} 
let sorted = Object.entries(toSort ).sort((a,b)=> a[1]-b[1]) 

输出:

[ [ "b", 14 ], [ "c", 799 ], [ "a", 2323 ] ]

下划线。js或Lodash.js用于高级数组或对象排序

var data = { "models": { "LTI": [ "TX" ], "Carado": [ "A", "T", "A(пасс)", "A(груз)", "T(пасс)", "T(груз)", "A", "T" ], "SPARK": [ "SP110C 2", "sp150r 18" ], "Autobianchi": [ "A112" ] } }; var arr = [], obj = {}; for (var i in data.models) { arr.push([i, _.sortBy(data.models[i], function(el) { return el; })]); } arr = _.sortBy(arr, function(el) { return el[0]; }); _.map(arr, function(el) { return obj[el[0]] = el[1]; }); console.log(obj); <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js" integrity="sha256-qXBd/EfAdjOA2FGrGAG+b3YBn2tn5A6bhz+LSgYD96k=" crossorigin="anonymous"></script>

我们不想复制整个数据结构,也不想在需要关联数组的地方使用数组。

这里有另一种方法来做与bonna相同的事情:

var列表={“我”“你”:100:75年,“foo”:116年,“酒吧”:15}; keysSorted = Object.keys(list).sort(function(a,b){返回list[a]-list[b]}) console.log (keysSorted);/ /酒吧,我,你,foo

一个过时问题的后续答案。我写了两个函数,一个是按键排序,另一个是按值排序,并在两个函数中以排序形式返回对象。它也应该在字符串上工作,因为这就是我张贴这个的原因(如果值不是数字的话,上面的一些按值排序有困难)。

const a = { absolutely: "works", entirely: 'zen', best: 'player', average: 'joe' } const prop_sort = obj => { return Object.keys(obj) .sort() .reduce((a, v) => { a[v] = obj[v]; return a; }, {}); } const value_sort = obj => { const ret = {} Object.values(obj) .sort() .forEach(val => { const key = Object.keys(obj).find(key => obj[key] == val) ret[key] = val }) return ret } console.log(prop_sort(a)) console.log(value_sort(a))

找不到上面的答案,既工作又小,并支持嵌套对象(不是数组),所以我写了自己的一个:)工作与字符串和整数。

  function sortObjectProperties(obj, sortValue){
      var keysSorted = Object.keys(obj).sort(function(a,b){return obj[a][sortValue]-obj[b][sortValue]});
      var objSorted = {};
      for(var i = 0; i < keysSorted.length; i++){
          objSorted[keysSorted[i]] = obj[keysSorted[i]];
      }
      return objSorted;
    }

用法:

    /* sample object with unsorder properties, that we want to sort by 
    their "customValue" property */

    var objUnsorted = {
       prop1 : {
          customValue : 'ZZ'
       },
       prop2 : {
          customValue : 'AA'
       }
    }

    // call the function, passing object and property with it should be sorted out
    var objSorted = sortObjectProperties(objUnsorted, 'customValue');

    // now console.log(objSorted) will return:
    { 
       prop2 : {
          customValue : 'AA'
       },
       prop1 : {
          customValue : 'ZZ'
       } 
    }