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

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

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

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

当前回答

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

function sortAssocObject(list) {
    var sortable = [];
    for (var key in list) {
        sortable.push([key, list[key]]);
    }
    // [["you",100],["me",75],["foo",116],["bar",15]]

    sortable.sort(function(a, b) {
        return (a[1] < b[1] ? -1 : (a[1] > b[1] ? 1 : 0));
    });
    // [["bar",15],["me",75],["you",100],["foo",116]]

    var orderedList = {};
    for (var idx in sortable) {
        orderedList[sortable[idx][0]] = sortable[idx][1];
    }

    return orderedList;
}

sortAssocObject(list);

// {bar: 15, me: 75, you: 100, foo: 116}

其他回答

找出每个元素的频率,并按频率/值进行排序。

Let response =["苹果","橘子","苹果","香蕉","橘子","香蕉","香蕉"]; 设frequency = {}; response.forEach(函数(项){ 频率[项目]=频率[项目]?频率[项]+ 1:1; }); console.log(频率); let intents = Object.entries(frequency) .sort((a, b) => b[1] - a[1]) . map(函数(x) { 返回x [0]; }); console.log(意图);

输出:

{ apple: 2, orange: 2, banana: 3 }
[ 'banana', 'apple', 'orange' ]

打印稿

下面的函数根据值或值的属性对对象进行排序。如果你不使用TypeScript,你可以删除类型信息,将其转换为JavaScript。

/**
 * Represents an associative array of a same type.
 */
interface Dictionary<T> {
  [key: string]: T;
}

/**
 * Sorts an object (dictionary) by value or property of value and returns
 * the sorted result as a Map object to preserve the sort order.
 */
function sort<TValue>(
  obj: Dictionary<TValue>,
  valSelector: (val: TValue) => number | string,
) {
  const sortedEntries = Object.entries(obj)
    .sort((a, b) =>
      valSelector(a[1]) > valSelector(b[1]) ? 1 :
      valSelector(a[1]) < valSelector(b[1]) ? -1 : 0);
  return new Map(sortedEntries);
}

使用

var list = {
  "one": { height: 100, weight: 15 },
  "two": { height: 75, weight: 12 },
  "three": { height: 116, weight: 9 },
  "four": { height: 15, weight: 10 },
};

var sortedMap = sort(list, val => val.height);

JavaScript对象中键的顺序是不保证的,所以我将排序并将结果返回为一个保留排序顺序的Map对象。

如果你想把它转换回Object,你可以这样做:

var sortedObj = {} as any;
sortedMap.forEach((v,k) => { sortedObj[k] = v });

没有多个for循环的排序值(按键排序将排序回调中的索引更改为“0”)

Const list = { “你”:100年, “我”:75年, “foo”:116年, “酒吧”:15 }; let sorted = Object.fromEntries( Object.entries(列表)。排序((a,b) => a[1] - b[1]) ) console.log('已排序对象:',已排序)

按值排序对象属性

Const obj ={你:100,我:75,foo: 116, bar: 15}; const keysSorted = Object.keys(obj)。排序((a, b) => obj[a] - obj[b]); Const result = {}; keysSorted。forEach(key => {result[key] = obj[key];}); 文档。write('Result: ' + JSON.stringify(Result));

期望的输出:

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

引用:

按值排序对象属性 将数组转换为对象

感谢@orad在TypeScript中提供了答案。现在,我们可以在JavaScript中使用下面的代码片断。

function sort(obj,valSelector) { const sortedEntries = Object.entries(obj) .sort((a, b) => valSelector(a[1]) > valSelector(b[1]) ? 1 : valSelector(a[1]) < valSelector(b[1]) ? -1 : 0); return new Map(sortedEntries); } const Countries = { "AD": { "name": "Andorra", }, "AE": { "name": "United Arab Emirates", }, "IN": { "name": "India", }} // Sort the object inside object. var sortedMap = sort(Countries, val => val.name); // Convert to object. var sortedObj = {}; sortedMap.forEach((v,k) => { sortedObj[k] = v }); console.log(sortedObj); //Output: {"AD": {"name": "Andorra"},"IN": {"name": "India"},"AE": {"name": "United Arab Emirates"}}