[英]How to sort object by numeric keys with nesting?
我有 object 和数字键,按某个值分组,这就是它有嵌套的原因:
const toSort = {
'3': {
"key1": "test",
"key2": "test",
},
'testVslue': {
'1': {
"key1": "test",
"key2": "test",
},
'2': {
"key1": "test",
"key2": "test",
},
},
'4': {
"key1": "test",
"key2": "test",
},
}
尽管有嵌套,但如何按键增长对 object 进行排序,如下所示:
const sorted = {
'testVslue': {
'1': {
"key1": "test",
"key2": "test",
},
'2': {
"key1": "test",
"key2": "test",
},
},
'3': {
"key1": "test",
"key2": "test",
},
'4': {
"key1": "test",
"key2": "test",
},
}
https://exploringjs.com/es6/ch_oop-besides-classes.html#_traversal-order-of-properties
自己的财产钥匙:
按以下顺序检索 object 的所有自身属性的键:
console.log(toSort);
// 3 4 testValue
const sorted = {};
Object.keys(toSort).sort().forEach(function(key) {
sorted[key] = toSort[key];
});
console.log(sorted);
// 3 4 testValue
所以,另一种方法是把它分开。
const sortedInteger = {};
const sortedString = {};
Object.keys(toSort).sort().forEach(function(key) {
if (isNaN(key)) {
sortedString[key] = toSort[key];
}
else {
sortedInteger[key] = toSort[key];
}
});
console.log(sortedString);
console.log(sortedInteger);
或者使用 Map 怎么样
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
const sortedIntegerArray = [];
let sortedMap = new Map()
Object.keys(toSort).sort().forEach( (key) => {
if (isNaN(key)) {
sortedMap.set(key, toSort[key])
}
else {
sortedIntegerArray.push(key);
}
});
sortedIntegerArray.forEach( (key) => {
sortedMap.set(key, toSort[key])
});
console.log(sortedMap)
// Map {
// 'testValue' => {
// '1': { key1: 'test', key2: 'test' },
// '2': { key1: 'test', key2: 'test' }
// },
// '3' => { key1: 'test', key2: 'test' },
// '4' => { key1: 'test', key2: 'test' }
// }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.