The problem background

Customer service feedback the original data sent by the back end is inconsistent with the data displayed in the report. For example:

The original data
The date of data
20211123 xxxx
20211120 xxxx
20211128 xxxx
20211130 xxxx
20211210 xxxx
20211203 xxxx
Actual table presentation
The date of data
20211120 xxxx
20211123 xxxx
20211128 xxxx
20211130 xxxx
20211203 xxxx
20211210 xxxx

This is a spreadsheet, right? Will it sort automatically? So I looked at the other charts

The original data
type data
The teacher The most beautiful
The doctor The most beautiful
The programmer The most beautiful
Real data
type data
The teacher The most beautiful
The doctor The most beautiful
The programmer The most beautiful

This is different? How about this form? If the key is only a number, the auto-sort behavior will appear.

Troubleshoot problems

If you have a Bug on the line, look at the code in the commit log and find that the order of the array has changed during a data processing.

Problem orientation

const column0Array = Object.keys(column0Map).map((val) = > {
      // Process logic{... } arr.push(column0Map[val]); });Copy the code

Column0Map stores “information under each date”, like:

20211203: {{... }, 20211130: {... }, 20211128: {... }, 20211210: {... },... }Copy the code

Basically, you need to store it in an array according to the key of the column, but! Keys () is secretly sorted. Wide of the mark?

Verify the guess

Question why

Integer properties are sorted, others appear in creation order.

If the key is Number, the order will be sorted first. Otherwise, the order will be original

The solution

1. Maintain the arR of an original key to ensure the order, like:

    const keysArr = [20211203.20211130.20211128.20211210];
    keysArr.forEach(() = >{... })Copy the code

2. Alter data structure to array like:

    const keysArr = [{key:20211203.value: {... }},... ] ; keysArr.forEach(() = >{... })Copy the code

conclusion

Object traversal is not guaranteed order, for the need to ensure the order of the data, can be converted to array first, is the matter of an extra key ~