如果我有一个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
};
当前回答
另一个关于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
}
希望这对你有所帮助!
其他回答
使用query-js你可以这样做
list.keys().select(function(k){
return {
key: k,
value : list[k]
}
}).orderBy(function(e){ return e.value;});
你可以在这里找到一篇关于query-js的介绍性文章
输入是对象,输出是对象,使用lodash & js内置库,降序或升序选项,不改变输入对象
Eg输入输出
{
"a": 1,
"b": 4,
"c": 0,
"d": 2
}
{
"b": 4,
"d": 2,
"a": 1,
"c": 0
}
实现
const _ = require('lodash');
const o = { a: 1, b: 4, c: 0, d: 2 };
function sortByValue(object, descending = true) {
const { max, min } = Math;
const selector = descending ? max : min;
const objects = [];
const cloned = _.clone(object);
while (!_.isEmpty(cloned)) {
const selectedValue = selector(...Object.values(cloned));
const [key, value] = Object.entries(cloned).find(([, value]) => value === selectedValue);
objects.push({ [key]: value });
delete cloned[key];
}
return _.merge(...objects);
}
const o2 = sortByValue(o);
console.log(JSON.stringify(o2, null, 2));
感谢@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"}}
非常简短简单!
var sortedList = {};
Object.keys(list).sort((a,b) => list[a]-list[b]).forEach((key) => {
sortedList[key] = list[key]; });
我用sort的解决方案:
let list = {
"you": 100,
"me": 75,
"foo": 116,
"bar": 15
};
let sorted = Object.entries(list).sort((a,b) => a[1] - b[1]);
for(let element of sorted) {
console.log(element[0]+ ": " + element[1]);
}