简体   繁体   English

按key升序对object进行排序

[英]Sort object by keys in ascending order

I currently have an object like this我目前有一个像这样的 object

let obj = {
    "5": "961131",
    "8": "961127",
    "5,5": "961107",
    "7": "961103",
    "9.5": "961115"
}

Is it possible to sort it by its keys in ascending order?是否可以按其键按升序对其进行排序? The result I want to achieve would be:我想要达到的结果是:

obj = {
    "5": "961131",
    "5,5": "961107",
    "7": "961103",
    "8": "961127",
    "9.5": "961115"
}

It would probably involve creating a new object which I don't mind, just not sure how to get this done它可能涉及创建一个新的 object 我不介意,只是不确定如何完成

You can't .你不能 Object keys are not sortable and you can't predict how each browser will iterate through object. Object 键不可排序,您无法预测每个浏览器将如何迭代 object。

But you can use an array as index like this.但是您可以像这样使用数组作为索引 Remember to format your keys.请记住格式化您的密钥。 If it's a string, juste use .sort() .如果是字符串,请使用.sort() Else you should probably compare your keys with .sort((a, b) => parseFloat(a) - parseFloat(b));否则,您可能应该将您的键与.sort((a, b) => parseFloat(a) - parseFloat(b));进行比较

 let obj = { "5": "961131", "8": "961127", "5,5": "961107", "7": "961103", "9.5": "961115" } let index = Object.keys(obj).sort() // iterate method index.forEach((key) => { console.log(key, obj[key]) }) // or array of sorted object let sortedArrayOfObject = index.map((v) => { return {key: v, value: obj[v]} }) console.log(sortedArrayOfObject)

let obj = {
    "5": "961131",
    "8": "961127",
    "5,5": "961107",
    "7": "961103",
    "9.5": "961115"
}
const objSortedByKeys = Object.fromEntries(Object.entries(obj).sort((a,b)=>a[0].localeCompare(b[0])));

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

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