按值对对象属性进行排序

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

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

有没有一种方法可以根据价值对属性进行排序?所以我最终会得到

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

JavaScript对象根据定义是无序的(请参阅ECMAScript语言规范,第8.6节)。语言规范甚至不能保证,如果您连续两次迭代对象的属性,它们第二次会以相同的顺序出现。

如果您需要排序,请使用数组和Array.prototype.sort方法。

将它们移动到一个数组中,对该数组进行排序,然后将该数组用于您的目的。这是一个解决方案:

let maxSpeed = {car: 300,bike: 60,motorbike: 200,airplane: 1000,helicopter: 400,rocket: 8 * 60 * 60};let sortable = [];for (var vehicle in maxSpeed) {sortable.push([vehicle, maxSpeed[vehicle]]);}
sortable.sort(function(a, b) {return a[1] - b[1];});
// [["bike", 60], ["motorbike", 200], ["car", 300],// ["helicopter", 400], ["airplane", 1000], ["rocket", 28800]]

一旦你有了数组,你就可以按照你喜欢的顺序从数组中重建对象,从而准确地实现你想要做的事情。这在我所知道的所有浏览器中都可以工作,但它取决于实现的怪癖,并且随时可能中断。你永远不应该对JavaScript对象中元素的顺序做出假设。

let objSorted = {}sortable.forEach(function(item){objSorted[item[0]]=item[1]})

在ES8中,您可以使用Object.entries()将对象转换为数组:

const maxSpeed = {car: 300,bike: 60,motorbike: 200,airplane: 1000,helicopter: 400,rocket: 8 * 60 * 60};
const sortable = Object.entries(maxSpeed).sort(([,a],[,b]) => a-b).reduce((r, [k, v]) => ({ ...r, [k]: v }), {});
console.log(sortable);


在ES10中,您可以使用Object.fromEntries()将数组转换为对象。然后代码可以简化为:

const maxSpeed = {car: 300,bike: 60,motorbike: 200,airplane: 1000,helicopter: 400,rocket: 8 * 60 * 60};
const sortable = Object.fromEntries(Object.entries(maxSpeed).sort(([,a],[,b]) => a-b));
console.log(sortable);

为完整起见,此函数返回对象属性的排序数组

function sortObject(obj) {var arr = [];for (var prop in obj) {if (obj.hasOwnProperty(prop)) {arr.push({'key': prop,'value': obj[prop]});}}arr.sort(function(a, b) { return a.value - b.value; });//arr.sort(function(a, b) { return a.value.toLowerCase().localeCompare(b.value.toLowerCase()); }); //use this to sort as stringsreturn arr; // returns array}
var list = {"you": 100, "me": 75, "foo": 116, "bar": 15};var arr = sortObject(list);console.log(arr); // [{key:"bar", value:15}, {key:"me", value:75}, {key:"you", value:100}, {key:"foo", value:116}]

上面代码的JSFiddle在这里。此解决方案基于这篇文章

排序字符串的更新小提琴在这里。您可以从中删除两个额外的.toLowerCase()转换以进行区分大小写的字符串比较。

我遵循slebetman给出的解决方案(去阅读所有细节),但进行了调整,因为您的对象是非嵌套的。

// First create the array of keys/values so that we can sort it:var sort_array = [];for (var key in list) {sort_array.push({key:key,value:list[key]});}
// Now sort it:sort_array.sort(function(x,y){return x.value - y.value});
// Now process that object with it:for (var i=0;i<sort_array.length;i++) {var item = list[sort_array[i].key];
// now do stuff with each item}

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

这里有另一种方法来做同样的事情:

var list = {"you": 100, "me": 75, "foo": 116, "bar": 15};keysSorted = Object.keys(list).sort(function(a,b){return list[a]-list[b]})console.log(keysSorted);     // bar,me,you,foo

Underscore.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>

您的对象可以具有任意数量的属性,如果您将对象放入数组中,您可以选择按所需的任何对象属性、数字或字符串进行排序。考虑这个数组:

var arrayOfObjects = [{name: 'Diana',born: 1373925600000, // Mon, Jul 15 2013num: 4,sex: 'female'},{
name: 'Beyonce',born: 1366832953000, // Wed, Apr 24 2013num: 2,sex: 'female'},{name: 'Albert',born: 1370288700000, // Mon, Jun 3 2013num: 3,sex: 'male'},{name: 'Doris',born: 1354412087000, // Sat, Dec 1 2012num: 1,sex: 'female'}];

按出生日期排序,最老的先

// use slice() to copy the array and not just make a referencevar byDate = arrayOfObjects.slice(0);byDate.sort(function(a,b) {return a.born - b.born;});console.log('by date:');console.log(byDate);

按名称排序

var byName = arrayOfObjects.slice(0);byName.sort(function(a,b) {var x = a.name.toLowerCase();var y = b.name.toLowerCase();return x < y ? -1 : x > y ? 1 : 0;});
console.log('by name:');console.log(byName);

http://jsfiddle.net/xsM5s/16/

另一种方法来解决这个问题:

var res = [{"s1":5},{"s2":3},{"s3":8}].sort(function(obj1,obj2){var prop1;var prop2;for(prop in obj1) {prop1=prop;}for(prop in obj2) {prop2=prop;}//the above two for loops will iterate only once because we use it to find the keyreturn obj1[prop1]-obj2[prop2];});

//res将有结果数组

谢谢并继续回答@Nosredna

现在我们了解了对象需要转换为数组,然后对数组进行排序。这对于按字符串对数组(或转换后的对象到数组)进行排序很有用:

Object {6: Object, 7: Object, 8: Object, 9: Object, 10: Object, 11: Object, 12: Object}6: Objectid: "6"name: "PhD"obe_service_type_id: "2"__proto__: Object7: Objectid: "7"name: "BVC (BPTC)"obe_service_type_id: "2"__proto__: Object

//Sort optionsvar sortable = [];for (var vehicle in options)sortable.push([vehicle, options[vehicle]]);sortable.sort(function(a, b) {return a[1].name < b[1].name ? -1 : 1;});

//sortable => prints[Array[2], Array[2], Array[2], Array[2], Array[2], Array[2], Array[2]]0: Array[2]0: "11"1: Objectid: "11"name: "AS/A2"obe_service_type_id: "2"__proto__: Objectlength: 2__proto__: Array[0]1: Array[2]0: "7"1: Objectid: "7"name: "BVC (BPTC)"obe_service_type_id: "2"__proto__: Objectlength: 2

这可能是一个简单的方法来处理它作为一个真正的有序对象。不确定它有多慢。也可能是更好的与同时循环。

Object.sortByKeys = function(myObj){var keys = Object.keys(myObj)keys.sort()var sortedObject = Object()for(i in keys){key = keys[i]sortedObject[key]=myObj[key]}
return sortedObject
}

然后我发现这个反转函数来自:http://nelsonwells.net/2011/10/swap-object-key-and-values-in-javascript/

Object.invert = function (obj) {
var new_obj = {};
for (var prop in obj) {if(obj.hasOwnProperty(prop)) {new_obj[obj[prop]] = prop;}}
return new_obj;};

所以

var list = {"you": 100, "me": 75, "foo": 116, "bar": 15};var invertedList = Object.invert(list)var invertedOrderedList = Object.sortByKeys(invertedList)var orderedList = Object.invert(invertedOrderedList)

试试这个。即使您的对象没有您尝试排序的属性,也会得到处理。

只需通过发送带有对象的属性来调用它。

var sortObjectByProperty = function(property,object){
console.time("Sorting");var  sortedList      = [];emptyProperty   = [];tempObject      = [];nullProperty    = [];$.each(object,function(index,entry){if(entry.hasOwnProperty(property)){var propertyValue = entry[property];if(propertyValue!="" && propertyValue!=null){sortedList.push({key:propertyValue.toLowerCase().trim(),value:entry});}else{emptyProperty.push(entry);}}else{nullProperty.push(entry);}});
sortedList.sort(function(a,b){return a.key < b.key ? -1 : 1;//return a.key < b.key?-1:1;   // Asc//return a.key < b.key?1:-1;  // Desc});

$.each(sortedList,function(key,entry){tempObject[tempObject.length] = entry.value;});
if(emptyProperty.length>0){tempObject.concat(emptyProperty);}if(nullProperty.length>0){tempObject.concat(nullProperty);}console.timeEnd("Sorting");return tempObject;}

使用query-js你可以这样做

list.keys().select(function(k){return {key: k,value : list[k]}}).orderBy(function(e){ return e.value;});

您可以找到有关query-js这里的介绍性文章

我为此制作了一个插件,它接受1个未排序对象的arg,并返回一个已按prop值排序的对象。这将适用于所有2维对象,例如{"Nick": 28, "Bob": 52}

var sloppyObj = {'C': 78,'A': 3,'B': 4};
// Extend object to support sort methodfunction sortObj(obj) {"use strict";
function Obj2Array(obj) {var newObj = [];for (var key in obj) {if (!obj.hasOwnProperty(key)) return;var value = [key, obj[key]];newObj.push(value);}return newObj;}
var sortedArray = Obj2Array(obj).sort(function(a, b) {if (a[1] < b[1]) return -1;if (a[1] > b[1]) return 1;return 0;});
function recreateSortedObject(targ) {var sortedObj = {};for (var i = 0; i < targ.length; i++) {sortedObj[targ[i][0]] = targ[i][1];}return sortedObj;}return recreateSortedObject(sortedArray);}
var sortedObj = sortObj(sloppyObj);
alert(JSON.stringify(sortedObj));

这是一个按照预期工作的函数的演示http://codepen.io/nicholasabrams/pen/RWRqve?editors=001

许多类似的有用函数:https://github.com/shimondoodkin/groupbyfunctions/

function sortobj(obj){var keys=Object.keys(obj);var kva= keys.map(function(k,i){return [k,obj[k]];});kva.sort(function(a,b){if(a[1]>b[1]) return -1;if(a[1]<b[1]) return 1;return 0});var o={}kva.forEach(function(a){ o[a[0]]=a[1]})return o;}
function sortobjkey(obj,key){var keys=Object.keys(obj);var kva= keys.map(function(k,i){return [k,obj[k]];});kva.sort(function(a,b){k=key;      if(a[1][k]>b[1][k]) return -1;if(a[1][k]<b[1][k]) return 1;return 0});var o={}kva.forEach(function(a){ o[a[0]]=a[1]})return o;}

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

  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 bytheir "customValue" property */
var objUnsorted = {prop1 : {customValue : 'ZZ'},prop2 : {customValue : 'AA'}}
// call the function, passing object and property with it should be sorted outvar objSorted = sortObjectProperties(objUnsorted, 'customValue');
// now console.log(objSorted) will return:{prop2 : {customValue : 'AA'},prop1 : {customValue : 'ZZ'}}

ECMAScript 2017引入了Object.values / Object.entries。顾名思义,前者将对象的所有值聚合到一个数组中,后者将整个对象聚合到一个由[key, value]数组组成的数组中;Python相当于dict.values()dict.items()

这些功能使将任何哈希排序为有序对象变得非常容易。截至目前,只有一小部分JavaScript平台支持它们,但您可以在Firefox 47+上尝试。

编辑:现在支持所有现代浏览器!

let obj = {"you": 100, "me": 75, "foo": 116, "bar": 15};
let entries = Object.entries(obj);// [["you",100],["me",75],["foo",116],["bar",15]]
let sorted = entries.sort((a, b) => a[1] - b[1]);// [["bar",15],["me",75],["you",100],["foo",116]]

这里还有一个例子:

function sortObject(obj) {var arr = [];var prop;for (prop in obj) {if (obj.hasOwnProperty(prop)) {arr.push({'key': prop,'value': obj[prop]});}}arr.sort(function(a, b) {return a.value - b.value;});return arr; // returns array}var list = {car: 300,bike: 60,motorbike: 200,airplane: 1000,helicopter: 400,rocket: 8 * 60 * 60};var arr = sortObject(list);console.log(arr);

一个“箭头”版本的@marcus R's回答供参考

var myObj = { you: 100, me: 75, foo: 116, bar: 15 };keysSorted = Object.keys(myObj).sort((a, b) => myObj[a] - myObj[b]);alert(keysSorted); // bar,me,you,foo

更新:2017年4月这将返回上面定义的已排序的myObj对象。

const myObj = { you: 100, me: 75, foo: 116, bar: 15 };const result =Object.keys(myObj).sort((a, b) => myObj[a] - myObj[b]).reduce((_sortedObj, key) => ({..._sortedObj,[key]: myObj[key]}),{});document.write(JSON.stringify(result));

更新:2021年3月-Object.entries排序功能(根据评论更新)

const myObj = { you: 100, me: 75, foo: 116, bar: 15 };const result = Object.entries(myObj).sort((a, b) => a[1] - b[1]).reduce((_sortedObj, [k,v]) => ({..._sortedObj,[k]: v}), {})document.write(JSON.stringify(result));

使用ES6更新:如果您关心的是有一个排序的对象来迭代(这就是为什么我想象您希望您的对象属性排序),您可以使用地图对象。

您可以按排序顺序插入您的(键,值)对,然后执行for..of循环将保证让它们按您插入它们的顺序循环

var myMap = new Map();myMap.set(0, "zero");myMap.set(1, "one");for (var [key, value] of myMap) {console.log(key + " = " + value);}// 0 = zero// 1 = one
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 sortedObject = {}sortedObject = Object.keys(yourObject).sort((a, b) => {return yourObject[a] - yourObject[b]}).reduce((prev, curr, i) => {prev[i] = yourObject[curr]return prev}, {});

您可以根据您的要求自定义排序功能

好的,您可能知道,JavaScript有分类函数,用于对数组进行排序,但没有用于对象…

所以在这种情况下,我们需要以某种方式获取键的数组并对它们进行排序,这就是apis大部分时间都在数组中为您提供对象的原因,因为Array具有比对象文字更多的本机函数来使用它们,无论如何,快速解决方案是使用Object.key返回对象键的数组,我在下面创建了ES6函数,它为您完成工作,它在javascript中使用本机分类减少()函数:

function sortObject(obj) {return Object.keys(obj).sort().reduce((a, v) => {a[v] = obj[v];return a; }, {});}

现在你可以像这样使用它:

let myObject = {a: 1, c: 3, e: 5, b: 2, d: 4};let sortedMyObject = sortObject(myObject);

检查sortedMyObject,您可以看到按键排序的结果,如下所示:

{a: 1, b: 2, c: 3, d: 4, e: 5}

同样这样,主对象不会被触摸,我们实际上得到了一个新对象。

我还创建了下面的图像,以使函数步骤更加清晰,以防您需要更改它以自己的方式工作:

按属性值对JavaScript对象进行排序

按值排序的对象(DESC)

function sortObject(list) {var sortable = [];for (var key in list) {sortable.push([key, list[key]]);}
sortable.sort(function(a, b) {return (a[1] > b[1] ? -1 : (a[1] < b[1] ? 1 : 0));});
var orderedList = {};for (var i = 0; i < sortable.length; i++) {orderedList[sortable[i][0]] = sortable[i][1];}
return orderedList;}

如果我有这样一个物体,

var dayObj = {"Friday":["5:00pm to 12:00am"] ,"Wednesday":["5:00pm to 11:00pm"],"Sunday":["11:00am to 11:00pm"],"Thursday":["5:00pm to 11:00pm"],"Saturday":["11:00am to 12:00am"]}

想按天数排序,

我们应该先有DaySorterMap,

var daySorterMap = {// "sunday": 0, // << if sunday is first day of week"Monday": 1,"Tuesday": 2,"Wednesday": 3,"Thursday": 4,"Friday": 5,"Saturday": 6,"Sunday": 7}

发起一个单独的Object sortedDayObj,

var sortedDayObj={};Object.keys(dayObj).sort((a,b) => daySorterMap[a] - daySorterMap[b]).forEach(value=>sortedDayObj[value]= dayObj[value])

您可以返回排序的DayObj

    var list = {"you": 100,"me": 75,"foo": 116,"bar": 15};var tmpList = {};while (Object.keys(list).length) {var key = Object.keys(list).reduce((a, b) => list[a] > list[b] ? a : b);tmpList[key] = list[key];delete list[key];}list = tmpList;console.log(list); // { foo: 116, you: 100, me: 75, bar: 15 }
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}]

function sortObjByValue(list){var sortedObj = {}Object.keys(list).map(key => [key, list[key]]).sort((a,b) => a[1] > b[1] ? 1 : a[1] < b[1] ? -1 : 0).forEach(data => sortedObj[data[0]] = data[1]);return sortedObj;}sortObjByValue(list);

Github GistLink

以防万一,有人正在寻找保留对象(带有键和值),使用@Markus R和@James Moran注释的代码引用,只需使用:

var list = {"you": 100, "me": 75, "foo": 116, "bar": 15};var newO = {};Object.keys(list).sort(function(a,b){return list[a]-list[b]}).map(key => newO[key] = list[key]);console.log(newO);  // {bar: 15, me: 75, you: 100, foo: 116}

在没有多个for循环的情况下对值进行排序(通过键进行排序,将排序回调中的索引更改为“0”)

const list = {"you": 100,"me": 75,"foo": 116,"bar": 15};
let sorted = Object.fromEntries(Object.entries(list).sort( (a,b) => a[1] - b[1] ))console.log('Sorted object: ', sorted) 

非常简短和简单!

var sortedList = {};Object.keys(list).sort((a,b) => list[a]-list[b]).forEach((key) => {sortedList[key] = list[key]; });

TypeScript

以下函数按值或值的属性对对象进行排序。如果您不使用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 });

输入是对象,输出是对象,使用Lodash&js内置lib,有降序或升序选项,不变异输入对象

eg输入输出

{"a": 1,"b": 4,"c": 0,"d": 2}{"b": 4,"d": 2,"a": 1,"c": 0}

的执行

const _ = require('lodash');
const o = { a: 1, b: 4, c: 0, d: 2 };

function sortByValue(object, descending = true) {const { max, min } = Math;const selector = descending ? max : min;
const objects = [];const cloned = _.clone(object);
while (!_.isEmpty(cloned)) {const selectedValue = selector(...Object.values(cloned));const [key, value] = Object.entries(cloned).find(([, value]) => value === selectedValue);
objects.push({ [key]: value });delete cloned[key];}
return _.merge(...objects);}
const o2 = sortByValue(o);console.log(JSON.stringify(o2, null, 2));
const arrayOfObjects = [{name: 'test'},{name: 'test2'}]
const order = ['test2', 'test']
const setOrder = (arrayOfObjects, order) =>arrayOfObjects.sort((a, b) => {if (order.findIndex((i) => i === a.name) < order.findIndex((i) => i === b.name)) {return -1;}
if (order.findIndex((i) => i === a.name) > order.findIndex((i) => i === b.name)) {return 1;}
return 0;});
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 ] ]

我的排序解决方案:

let list = {"you": 100,"me": 75,"foo": 116,"bar": 15};
let sorted = Object.entries(list).sort((a,b) => a[1] - b[1]);
for(let element of sorted) {console.log(element[0]+ ": " + element[1]);}
<pre>function sortObjectByVal(obj){var keysSorted = Object.keys(obj).sort(function(a,b){return obj[b]-obj[a]});var newObj = {};for(var x of keysSorted){newObj[x] = obj[x];}return newObj;
}var list = {"you": 100, "me": 75, "foo": 116, "bar": 15};console.log(sortObjectByVal(list));</pre>

有很多方法可以做到这一点,但是因为我没有看到任何使用reduce()的方法,所以我把它放在这里。也许它对某人来说似乎很有用。

var list = {"you": 100,"me": 75,"foo": 116,"bar": 15};
let result = Object.keys(list).sort((a,b)=>list[a]>list[b]?1:-1).reduce((a,b)=> {a[b]=list[b]; return a},{});
console.log(result);

查找每个元素的频率并按频率/值对其进行排序。

let response = ["apple", "orange", "apple", "banana", "orange", "banana", "banana"];let frequency = {};response.forEach(function(item) {frequency[item] = frequency[item] ? frequency[item] + 1 : 1;});console.log(frequency);let intents = Object.entries(frequency).sort((a, b) => b[1] - a[1]).map(function(x) {return x[0];});console.log(intents);

产出:

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

感谢@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"}}

按值对对象属性进行排序

const obj = { you: 100, me: 75, foo: 116, bar: 15 };const keysSorted = Object.keys(obj).sort((a, b) => obj[a] - obj[b]);const result = {};keysSorted.forEach(key => { result[key] = obj[key]; });document.write('Result: ' + JSON.stringify(result));

期望的输出:

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

参考文献:

另一个例子是Object.valuessort()spread operator

var paintings = {0: {title: 'Oh my!',year: '2020',price: '3000'},1: {title: 'Portrait V',year: '2021',price: '2000'},2: {title: 'The last leaf',year: '2005',price: '600'}}

我们将对象转换为具有Object.values的对象数组:

var toArray = Object.values(paintings)

然后我们对数组进行排序(按年份和价格),使用spread operator使原始数组不可变,使用sort()方法对数组进行排序:

var sortedByYear = [...toArray].sort((a, b) => a.year - b.year)var sortedByPrice = [...toArray].sort((a, b) => a.price - b.price)

最后,我们生成新的排序对象(再次使用spread operator来保持对象的原始形式,并使用[x: number]作为键):

var paintingsSortedByYear = {...sortedByYear}
var paintingsSortedByPrice = {...sortedByPrice}

希望这能有所帮助!

我用自己的方式尝试过

var maxSpeed = {car: 300,bike: 60,motorbike: 200,airplane: 1000,helicopter: 400,rocket: 8 * 60 * 60};var sorted = {}Object.keys(maxSpeed).sort ((a,b) => maxSpeed[a] - maxSpeed[b]).map(item => sorted[item] = maxSpeed[item]);console.log(sorted)

一个过时的问题的后续答案。我写了两个函数,一个按键排序,另一个按值排序,并在两个函数中以排序形式返回对象。它也应该适用于字符串,因为这就是我发布这个的原因(如果值不是数字,则很难使用上面的一些按值排序)。

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))

下面是工作代码

var list = {"you": 100,"me": 75,"foo": 116,"bar": 15};var sortArray = [];
// convert the list to array of key and value pairfor(let  i in list){sortArray.push({key : i, value:list[i]});}
//console.log(sortArray);// sort the array using value.sortArray.sort(function(a,b){return a.value - b.value;});
//console.log(sortArray);
// now create a newList of required format.let newList={};for(let i in sortArray){newList[sortArray[i].key] = sortArray[i].value;}
console.log(newList);