简体   繁体   English

如何通过嵌套的数字键对 object 进行排序?

[英]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:我有 object 和数字键,按某个值分组,这就是它有嵌套的原因:

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:尽管有嵌套,但如何按键增长对 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 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:按以下顺序检索 object 的所有自身属性的键:

  • First, the string keys that are integer indices (what these are is explained in the next section), in ascending numeric order.首先,字符串键是 integer 索引(这些是什么在下一节中解释),按数字升序排列。
  • Then all other string keys, in the order in which they were added to the object.然后所有其他字符串键,按照它们被添加到 object 的顺序。
  • Lastly, all symbol keys, in the order in which they were added to the object.最后,所有符号键,按照它们被添加到 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或者使用 Map 怎么样
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/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.

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