简体   繁体   English

如何在ASC中对javascript对象键进行排序

[英]How to sort javascript object key in ASC

I want to sort object keys in ASC .My keys is string and number so try with sort is not solve . 我想在ASC中对对象键进行排序。我的键是字符串和数字,所以尝试使用sort无法解决。

//sorting number function
function sortNum(a,b) {
    return a - b;
}
let obj = {key10:10,key2:2,key5:5,key1:1};
let ordered = {};
Object.keys(obj).sort().forEach(function(key,v){
    ordered[key] = v;
});
console.log(ordered); //{key1: 1, key10: 10, key2: 2, key5: 5}
//try with sort number function
//Object.keys(obj).sort(sortNum).forEach(function(key){
//ordered[key] = obj[key];
//});
//console.log(ordered); -> {key10: 10, key2: 2, key5: 5, key1: 1}

Expected => {key1: 1, key2: 2, key5: 5, key10: 10} 期望=> {key1: 1, key2: 2, key5: 5, key10: 10}

Since they all have the same start (key), sort by comparing the numbers. 由于它们都有相同的开始(键),因此可以通过比较数字进行排序。

I've stored it as an array that you can just use to access the original object. 我将其存储为一个数组,您可以使用它来访问原始对象。

 let obj = {key10:10,key2:2,key5:5,key1:1}; var ordered = Object.keys(obj).sort( (a,b) => { let numA = a.match(/\\d+/); let numB = b.match(/\\d+/); return +numA - +numB; }); console.log(ordered); 

Try with Array#sort sorting with ASC order and Array#reduce used for return with object .Finally /(\\d+)/ used for find the numbers in the key 尝试使用ASC顺序Array#sort排序,将Array#reduce用于与对象.Finally一起返回,最后/(\\d+)/用于在键中查找数字

 let obj = {key10:10,key2:2,key5:5,key1:1}; var ordered = Object.keys(obj).sort((a,b)=>{ return parseInt(a.match(/(\\d+)/)) < parseInt(b.match(/(\\d+)/)) ? -1 : parseInt(a.match(/(\\d+)/)) > parseInt(b.match(/(\\d+)/)) ? 1 :0; }).reduce((a,b) => (a[b]=obj[b] ,a),{}) console.log(ordered); 

I used the Array.prototype methods to map and reduce your collection in your sorted collection. 我使用了Array.prototype方法来映射并减少已排序集合中的集合。 Read the comments and let me know if you need more clarification! 阅读评论,让我知道是否需要进一步说明!

 let obj = { key10: 10, key2: 2, key5: 5, key1: 1 }; let ordered = (Object // creates an array of keys .keys(obj) // map each key into a tuples of {key, value} objects .map(key => ({ key, value: obj[key] })) // sort those objects by the value .sort((a, b) => a.value - b.value) // then reduce back into another object .reduce((ordered, {key, value}) => { ordered[key] = value; return ordered; }, {}) ); console.log(ordered); 

You could use both parts of the string, nonnumerical, sort by string and the numerical part, sort by number with a regular expression. 您可以使用字符串的两个部分,非数字部分,按字符串排序,数字部分,按数字排序,并使用正则表达式。

 let obj = { key10: 10, key2: 2, key5: 5, key1: 1, foo1000: 1000, foo0: 0, foo20: 20 }, keys = Object.keys(obj); keys.sort(function (a, b) { function parts(s) { return s.match(/\\D+|\\d+/g); } var aa = parts(a), bb = parts(b); return aa[0].localeCompare(bb[0]) || aa[1] - bb[1]; }); console.log(keys); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM