I have object with numeric keys, grouped by some value, that`s why it have nesting:
const toSort = {
'3': {
"key1": "test",
"key2": "test",
},
'testVslue': {
'1': {
"key1": "test",
"key2": "test",
},
'2': {
"key1": "test",
"key2": "test",
},
},
'4': {
"key1": "test",
"key2": "test",
},
}
How can I sort the object by key growth, despite the nesting, like this:
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
Own Property Keys:
Retrieves the keys of all own properties of an object, in the following order:
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
so, other way is to divide it up.
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);
or how about use 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' }
// }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.