如果我有一个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
};
当前回答
使用query-js你可以这样做
list.keys().select(function(k){
return {
key: k,
value : list[k]
}
}).orderBy(function(e){ return e.value;});
你可以在这里找到一篇关于query-js的介绍性文章
其他回答
输入是对象,输出是对象,使用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));
另一种解决方法:-
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将有结果数组
谢谢你,继续回答@Nosredna
现在我们知道对象需要转换为数组,然后对数组排序。这对于按字符串排序数组(或转换对象为数组)非常有用:
Object {6: Object, 7: Object, 8: Object, 9: Object, 10: Object, 11: Object, 12: Object}
6: Object
id: "6"
name: "PhD"
obe_service_type_id: "2"
__proto__: Object
7: Object
id: "7"
name: "BVC (BPTC)"
obe_service_type_id: "2"
__proto__: Object
//Sort options
var 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: Object
id: "11"
name: "AS/A2"
obe_service_type_id: "2"
__proto__: Object
length: 2
__proto__: Array[0]
1: Array[2]
0: "7"
1: Object
id: "7"
name: "BVC (BPTC)"
obe_service_type_id: "2"
__proto__: Object
length: 2
如果我有一个这样的对象,
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
}
初始化一个单独的对象sortedDayObj,
var sortedDayObj={};
Object.keys(dayObj)
.sort((a,b) => daySorterMap[a] - daySorterMap[b])
.forEach(value=>sortedDayObj[value]= dayObj[value])
你可以返回sortedDayObj
将它们移动到一个数组中,对该数组进行排序,然后将该数组用于您的目的。这里有一个解决方案:
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 = { 车:300, 自行车:60岁 摩托车:200, 飞机:1000, 直升机:400, 火箭:8 * 60 * 60 }; const sortable = Object.entries(maxSpeed) .sort([,a],[,b]) => a-b) .reduce((r, [k, v]) =>({…R, [k]: v}), {}); console.log(合适的);
在ES10中,你可以使用object. fromentries()将数组转换为对象。然后代码可以简化为:
const maxSpeed = { 车:300, 自行车:60岁 摩托车:200, 飞机:1000, 直升机:400, 火箭:8 * 60 * 60 }; const sortable = Object.fromEntries( Object.entries(maxSpeed).sort(([,a],[,b]) => a-b) ); console.log(合适的);