如果我有一个JavaScript对象,如:
var list = {
"you": 100,
"me": 75,
"foo": 116,
"bar": 15
};
是否有一种方法可以根据值对属性进行排序?最后得到
list = {
"bar": 15,
"me": 75,
"you": 100,
"foo": 116
};
如果我有一个JavaScript对象,如:
var list = {
"you": 100,
"me": 75,
"foo": 116,
"bar": 15
};
是否有一种方法可以根据值对属性进行排序?最后得到
list = {
"bar": 15,
"me": 75,
"you": 100,
"foo": 116
};
当前回答
另一种解决方法:-
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 key
return obj1[prop1]-obj2[prop2];
});
//res将有结果数组
其他回答
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 Gist Link
我遵循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
}
为了完整起见,这个函数返回对象属性的排序数组:
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 strings
return 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()转换,以便区分大小写的字符串比较。
对象按值排序(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;
}
输入是对象,输出是对象,使用lodash & js内置库,降序或升序选项,不改变输入对象
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));