如果我有一个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
};
当前回答
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;
});
其他回答
我遵循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 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将有结果数组
非常简短简单!
var sortedList = {};
Object.keys(list).sort((a,b) => list[a]-list[b]).forEach((key) => {
sortedList[key] = list[key]; });
以防万一,有人正在寻找保持对象(键和值),使用@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}
<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>