简体   繁体   中英

How to sort object by numeric keys with nesting?

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:

  • First, the string keys that are integer indices (what these are is explained in the next section), in ascending numeric order.
  • Then all other string keys, in the order in which they were added to the object.
  • Lastly, all symbol keys, in the order in which they were added to the 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

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.

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