如果我有一个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
};
当前回答
使用query-js你可以这样做
list.keys().select(function(k){
return {
key: k,
value : list[k]
}
}).orderBy(function(e){ return e.value;});
你可以在这里找到一篇关于query-js的介绍性文章
其他回答
我用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]);
}
下划线。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>
这是获取排序对象和返回排序对象的方法
let sortedObject = {}
sortedObject = Object.keys(yourObject).sort((a, b) => {
return yourObject[a] - yourObject[b]
}).reduce((prev, curr, i) => {
prev[i] = yourObject[curr]
return prev
}, {});
您可以根据您的需求自定义排序功能
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;
});
我为此做了一个插件,它接受1个arg,这是一个未排序的对象,并返回一个对象,已排序的道具值。这将适用于所有二维对象,如{"Nick": 28, "Bob": 52}…
var sloppyObj = {
'C': 78,
'A': 3,
'B': 4
};
// Extend object to support sort method
function sortObj(obj) {
"use strict";
function Obj2Array(obj) {
var newObj = [];
for (var key in obj) {
if (!obj.hasOwnProperty(key)) return;
var value = [key, obj[key]];
newObj.push(value);
}
return newObj;
}
var sortedArray = Obj2Array(obj).sort(function(a, b) {
if (a[1] < b[1]) return -1;
if (a[1] > b[1]) return 1;
return 0;
});
function recreateSortedObject(targ) {
var sortedObj = {};
for (var i = 0; i < targ.length; i++) {
sortedObj[targ[i][0]] = targ[i][1];
}
return sortedObj;
}
return recreateSortedObject(sortedArray);
}
var sortedObj = sortObj(sloppyObj);
alert(JSON.stringify(sortedObj));
下面是该函数按预期工作的演示 http://codepen.io/nicholasabrams/pen/RWRqve?editors=001