如果我有一个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
};
当前回答
下划线。js或Lodash.js用于高级数组或对象排序
var data = { "models": { "LTI": [ "TX" ], "Carado": [ "A", "T", "A(пасс)", "A(груз)", "T(пасс)", "T(груз)", "A", "T" ], "SPARK": [ "SP110C 2", "sp150r 18" ], "Autobianchi": [ "A112" ] } }; var arr = [], obj = {}; for (var i in data.models) { arr.push([i, _.sortBy(data.models[i], function(el) { return el; })]); } arr = _.sortBy(arr, function(el) { return el[0]; }); _.map(arr, function(el) { return obj[el[0]] = el[1]; }); console.log(obj); <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js" integrity="sha256-qXBd/EfAdjOA2FGrGAG+b3YBn2tn5A6bhz+LSgYD96k=" crossorigin="anonymous"></script>
其他回答
以防万一,有人正在寻找保持对象(键和值),使用@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}
如果我有一个这样的对象,
var dayObj = {
"Friday":["5:00pm to 12:00am"] ,
"Wednesday":["5:00pm to 11:00pm"],
"Sunday":["11:00am to 11:00pm"],
"Thursday":["5:00pm to 11:00pm"],
"Saturday":["11:00am to 12:00am"]
}
我想按天排序,
我们应该先有daySorterMap,
var daySorterMap = {
// "sunday": 0, // << if sunday is first day of week
"Monday": 1,
"Tuesday": 2,
"Wednesday": 3,
"Thursday": 4,
"Friday": 5,
"Saturday": 6,
"Sunday": 7
}
初始化一个单独的对象sortedDayObj,
var sortedDayObj={};
Object.keys(dayObj)
.sort((a,b) => daySorterMap[a] - daySorterMap[b])
.forEach(value=>sortedDayObj[value]= dayObj[value])
你可以返回sortedDayObj
使用query-js你可以这样做
list.keys().select(function(k){
return {
key: k,
value : list[k]
}
}).orderBy(function(e){ return e.value;});
你可以在这里找到一篇关于query-js的介绍性文章
对象按值排序(DESC)
function sortObject(list) {
var sortable = [];
for (var key in list) {
sortable.push([key, list[key]]);
}
sortable.sort(function(a, b) {
return (a[1] > b[1] ? -1 : (a[1] < b[1] ? 1 : 0));
});
var orderedList = {};
for (var i = 0; i < sortable.length; i++) {
orderedList[sortable[i][0]] = sortable[i][1];
}
return orderedList;
}
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;
});