如果我有一个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
};
当前回答
以防万一,有人正在寻找保持对象(键和值),使用@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}
其他回答
另一种解决方法:-
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将有结果数组
感谢@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"}}
<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>
使用query-js你可以这样做
list.keys().select(function(k){
return {
key: k,
value : list[k]
}
}).orderBy(function(e){ return e.value;});
你可以在这里找到一篇关于query-js的介绍性文章
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}]