如果我有一个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 arrayOfObjects = [
{
name: 'Diana',
born: 1373925600000, // Mon, Jul 15 2013
num: 4,
sex: 'female'
},
{
name: 'Beyonce',
born: 1366832953000, // Wed, Apr 24 2013
num: 2,
sex: 'female'
},
{
name: 'Albert',
born: 1370288700000, // Mon, Jun 3 2013
num: 3,
sex: 'male'
},
{
name: 'Doris',
born: 1354412087000, // Sat, Dec 1 2012
num: 1,
sex: 'female'
}
];
按出生日期排序,最年长的先
// use slice() to copy the array and not just make a reference
var 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/
其他回答
一个过时问题的后续答案。我写了两个函数,一个是按键排序,另一个是按值排序,并在两个函数中以排序形式返回对象。它也应该在字符串上工作,因为这就是我张贴这个的原因(如果值不是数字的话,上面的一些按值排序有困难)。
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))
谢谢你,继续回答@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 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}
我们不想复制整个数据结构,也不想在需要关联数组的地方使用数组。
这里有另一种方法来做与bonna相同的事情:
var列表={“我”“你”:100:75年,“foo”:116年,“酒吧”:15}; keysSorted = Object.keys(list).sort(function(a,b){返回list[a]-list[b]}) console.log (keysSorted);/ /酒吧,我,你,foo
找不到上面的答案,既工作又小,并支持嵌套对象(不是数组),所以我写了自己的一个:)工作与字符串和整数。
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 by
their "customValue" property */
var objUnsorted = {
prop1 : {
customValue : 'ZZ'
},
prop2 : {
customValue : 'AA'
}
}
// call the function, passing object and property with it should be sorted out
var objSorted = sortObjectProperties(objUnsorted, 'customValue');
// now console.log(objSorted) will return:
{
prop2 : {
customValue : 'AA'
},
prop1 : {
customValue : 'ZZ'
}
}