The order of keys traversed by the front end is incorrect when traversing objects

When uniapp develops small programs, sometimes the data given by the backend is such a 日期:数据key-value pair given in this order:

    let o = {
    
    
      '2021-01-01 00:00:00': '1',
      '2021-02-01 00:00:00': '2',
      '2021-03-01 00:00:00': '3',
      '2021-04-01 00:00:00': '4',
      '2021-05-01 00:00:00': '5',
      '2021-06-01 00:00:00': '6',
      '2021-07-01 00:00:00': '7',
      '2021-08-01 00:00:00': '8',
      '2021-09-01 00:00:00': '9',
      '2021-10-01 00:00:00': '10',
      '2021-11-01 00:00:00': '11',
      '2021-12-01 00:00:00': '12',
      '2022-01-01 00:00:00': '1',
      '2022-02-01 00:00:00': '2',
      '2022-03-01 00:00:00': '3',
      '2022-04-01 00:00:00': '4',
      '2022-05-01 00:00:00': '5',
      '2022-06-01 00:00:00': '6',
      '2022-07-01 00:00:00': '7',
      '2022-08-01 00:00:00': '8',
      '2022-09-01 00:00:00': '9',
      '2022-10-01 00:00:00': '10',
      '2022-11-01 00:00:00': '11',
      '2022-12-01 00:00:00': '12',
    };
    
    for (let k in o) {
    
    
      console.log(k);
    }

However, using for...in... to loop through this object and print its key value, the order of final access may be inconsistent with the order given by the interface in the uniapp development applet, as follows:

image.png

This problem has never been encountered on the web side, but uniappthis problem occurred when processing the data given by the interface when using the development applet, which caused a bug. There are too many pitfalls in using uniapp to develop small programs, so I don’t want to go into the specific reasons. Here I just talk about the solutions:

    function sortDateFn(obj) {
    
    
      if (obj.toString() !== '[object Object]') return;
      /* 排序后的map */
      const newObj = {
    
    };
      const sortedKeys = Object.keys(obj).sort(
        (a, b) => new Date(a) - new Date(b)
      );

      /* 将排好序的日期与原map的数据绑定起来 */
      sortedKeys.forEach((k) => {
    
    
        newObj[k] = obj[k];
      });

      return newObj;
    }

The above method is to re-sort the key values ​​of the map, then traverse the sorted key values, and put the value corresponding to the original map object into the new map object.

Guess you like

Origin blog.csdn.net/vet_then_what/article/details/125515888