如果我有一个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 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}
其他回答
感谢@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"}}
一个过时问题的后续答案。我写了两个函数,一个是按键排序,另一个是按值排序,并在两个函数中以排序形式返回对象。它也应该在字符串上工作,因为这就是我张贴这个的原因(如果值不是数字的话,上面的一些按值排序有困难)。
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))
你的对象可以有任意数量的属性,如果你把对象放在数组中,你可以选择根据你想要的任何对象属性进行排序,数字或字符串。考虑这个数组:
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/
另一种解决方法:-
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 sortObjectByProperty = function(property,object){
console.time("Sorting");
var sortedList = [];
emptyProperty = [];
tempObject = [];
nullProperty = [];
$.each(object,function(index,entry){
if(entry.hasOwnProperty(property)){
var propertyValue = entry[property];
if(propertyValue!="" && propertyValue!=null){
sortedList.push({key:propertyValue.toLowerCase().trim(),value:entry});
}else{
emptyProperty.push(entry);
}
}else{
nullProperty.push(entry);
}
});
sortedList.sort(function(a,b){
return a.key < b.key ? -1 : 1;
//return a.key < b.key?-1:1; // Asc
//return a.key < b.key?1:-1; // Desc
});
$.each(sortedList,function(key,entry){
tempObject[tempObject.length] = entry.value;
});
if(emptyProperty.length>0){
tempObject.concat(emptyProperty);
}
if(nullProperty.length>0){
tempObject.concat(nullProperty);
}
console.timeEnd("Sorting");
return tempObject;
}