如果我有一个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
};
当前回答
function sortObjByValue(list){
var sortedObj = {}
Object.keys(list)
.map(key => [key, list[key]])
.sort((a,b) => a[1] > b[1] ? 1 : a[1] < b[1] ? -1 : 0)
.forEach(data => sortedObj[data[0]] = data[1]);
return sortedObj;
}
sortObjByValue(list);
Github Gist Link
其他回答
找不到上面的答案,既工作又小,并支持嵌套对象(不是数组),所以我写了自己的一个:)工作与字符串和整数。
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'
}
}
打印稿
下面的函数根据值或值的属性对对象进行排序。如果你不使用TypeScript,你可以删除类型信息,将其转换为JavaScript。
/**
* Represents an associative array of a same type.
*/
interface Dictionary<T> {
[key: string]: T;
}
/**
* Sorts an object (dictionary) by value or property of value and returns
* the sorted result as a Map object to preserve the sort order.
*/
function sort<TValue>(
obj: Dictionary<TValue>,
valSelector: (val: TValue) => number | string,
) {
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);
}
使用
var list = {
"one": { height: 100, weight: 15 },
"two": { height: 75, weight: 12 },
"three": { height: 116, weight: 9 },
"four": { height: 15, weight: 10 },
};
var sortedMap = sort(list, val => val.height);
JavaScript对象中键的顺序是不保证的,所以我将排序并将结果返回为一个保留排序顺序的Map对象。
如果你想把它转换回Object,你可以这样做:
var sortedObj = {} as any;
sortedMap.forEach((v,k) => { sortedObj[k] = v });
另一个关于Object的例子。值、sort()和展开运算符。
var paintings = {
0: {
title: 'Oh my!',
year: '2020',
price: '3000'
},
1: {
title: 'Portrait V',
year: '2021',
price: '2000'
},
2: {
title: 'The last leaf',
year: '2005',
price: '600'
}
}
我们使用object .values将对象转换为对象数组:
var toArray = Object.values(paintings)
然后我们对数组进行排序(按年份和价格),使用spread操作符使原始数组不可变,并使用sort()方法对数组进行排序:
var sortedByYear = [...toArray].sort((a, b) => a.year - b.year)
var sortedByPrice = [...toArray].sort((a, b) => a.price - b.price)
最后,我们生成新的排序对象(同样,使用展开运算符来保持以[x: number]为键的对象的object的原始形式):
var paintingsSortedByYear = {
...sortedByYear
}
var paintingsSortedByPrice = {
...sortedByPrice
}
希望这对你有所帮助!
我已经用自己的方式尝试过了
var maxSpeed = {
car: 300,
bike: 60,
motorbike: 200,
airplane: 1000,
helicopter: 400,
rocket: 8 * 60 * 60
};
var sorted = {}
Object.keys(maxSpeed).sort ((a,b) => maxSpeed[a] - maxSpeed[b]).map(item => sorted[item] = maxSpeed[item]);
console.log(sorted)
var list = {
"you": 100,
"me": 75,
"foo": 116,
"bar": 15
};
var tmpList = {};
while (Object.keys(list).length) {
var key = Object.keys(list).reduce((a, b) => list[a] > list[b] ? a : b);
tmpList[key] = list[key];
delete list[key];
}
list = tmpList;
console.log(list); // { foo: 116, you: 100, me: 75, bar: 15 }