如果我有一个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
};
当前回答
打印稿
下面的函数根据值或值的属性对对象进行排序。如果你不使用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 });
其他回答
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 }
使用query-js你可以这样做
list.keys().select(function(k){
return {
key: k,
value : list[k]
}
}).orderBy(function(e){ return e.value;});
你可以在这里找到一篇关于query-js的介绍性文章
ES6更新:如果你关心的是有一个排序的对象来迭代(这就是为什么我想象你想要你的对象属性排序),你可以使用Map对象。
您可以按顺序插入(key, value)对,然后执行for..of循环将确保它们按照您插入它们的顺序进行循环
var myMap = new Map();
myMap.set(0, "zero");
myMap.set(1, "one");
for (var [key, value] of myMap) {
console.log(key + " = " + value);
}
// 0 = zero
// 1 = one
下划线。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>
我用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]);
}