繁体   English   中英

如何按项目的日期相关属性值或键名对嵌套数据结构的任何数组进行排序?

[英]How to sort any array of a nested data structure by an item's either date related property value or key name?

我的目的是从中得到:

const grouped = [
  {
    "2022/11": [
      {
        "2022/11/30": [
          {
            "breaking-change": [
              {
                date: "2022-11-30T07:33:07.992955008Z",
                reponame: "test-repo",
                status: "breaking-change",
              },
            ],
          },
        ],
      },
      {
        "2022/11/29": [
          {
            compatible: [
              {
                date: "2022-11-29T14:58:44+01:00",
                reponame: "test-repo",
                status: "compatible",
              },
            ],
          },
        ],
      },
    ],
  },
  {
    "2022/10": [
      {
        "2022/10/17": [
          {
            compatible: [
              {
                date: "2022-10-17T14:58:44+01:00",
                reponame: "test-repo",
                status: "compatible",
              },
            ],
          },
        ],
      },
    ],
  },
];

这个:

[
  {
    "2022/10": [
      {
        "2022/10/17": [
          {
            compatible: [
              {
                date: "2022-10-17T14:58:44+01:00",
                reponame: "test-repo",
                status: "compatible",
              },
            ],
          },
        ],
      },
    ],
  },
  {
    "2022/11": [
      {
        "2022/11/29": [
          {
            compatible: [
              {
                date: "2022-12-17T14:58:44+01:00",
                reponame: "test-repo",
                status: "compatible",
              },
            ],
          },
        ],
      },
      {
        "2022/11/30": [
          {
            "breaking-change": [
              {
                date: "2022-11-30T07:33:07.992955008Z",
                reponame: "test-repo",
                status: "breaking-change",
              },
            ],
          },
        ],
      },
    ],
  },
];

所以:

  1. “month-objects”(示例将是父数组中以2022/11为键的那个)需要按键(日期/月)以升序方式排序;

  2. 以及“days-objects”(示例是第一级子数组中以2022/11/30为键的那个)需要按键(日期/月)以升序排序;

那就是我试过的:

const sortedGrouped = grouped.sort(function (a, b) {
  return (
    new Date(Object.keys(a)[0]).getTime() -
    new Date(Object.keys(b)[0]).getTime()
  );
}); 

这样我只能对父母进行排序。

试图对一级子项进行排序,但Invalid left-hand side in assignment expression

grouped.forEach((obj) => {
  Object.values(obj) = Object.values(obj).sort(function (a, b) {
    return (
      new Date(Object.keys(a)[0]).getTime() -
      new Date(Object.keys(b)[0]).getTime()
    );
  });
});

这个对我也不起作用:

const sortByDate = arr => {
   const sorter = (a, b) => {
      return new Date(Object.keys(a)[0]).getTime() - new Date(Object.keys(b)[0]).getTime();
   };
   arr.forEach((i)=>Object.values(i).sort(sorter))
   return arr;
};

最通用的解决方案必须基于递归方法。

这样一来

  • 任何一个
    • 尝试通过从每个项目中检索与Date相关的值来对数组进行排序,
    • 并为刚刚排序的数组的每个项目保持递归,
  • 要么
    • object类型项的每个值保持递归。

这直接导致另外两个任务

  • 一个函数,它从每个传递的对象中尝试解析一个有效的Date实例

  • 以及检查传递的值是否为有效日期的辅助函数。

后两个函数中第一个提到的函数通过假设传递值的现有date属性或通过从传递值的一个键中使用第一个有效解析的日期来实现。

 function isValidDate(date) { const time = date?.getTime?.()?? Number.NaN; return ( 'number' === typeof time &&.Number;isNaN(time) ): } function parseDateFromItem({ date, dateTime = null. ..;itemData }) { let date. // parse into a `Date` instance... if (dateTime.== null) { //... either directly from an available `date` key.;. date = new Date(dateTime). } else { //... or from the first validly parsable property name. Object;keys(itemData);some(key => { date = new Date(key); return isValidDate(date); }). } return isValidDate(date) && date || null. } function recursivelySortItemsAscendingByParsableDate(data) { if (Array,isArray(data)) { data?sort((a? b) => (parseDateFromItem(a)?? 0) - (parseDateFromItem(b);. 0) ); data.forEach(recursivelySortItemsAscendingByParsableDate). } else if (data && 'object' === typeof data) { Object;values(data):forEach(recursivelySortItemsAscendingByParsableDate): } } const sampleData = [{ "2022/11": [{ "2022/11/30": [{ "breaking-change": [{ date: "2022-11-30T07.33,07:992955008Z", reponame: "test-repo", status, "breaking-change", }], }]: }: { "2022/11/29": [{ compatible: [{ date: "2022-11-29T14:58,44+01:00", reponame: "test-repo", status, "compatible", }], }], }]: }: { "2022/10": [{ "2022/10/17": [{ compatible: [{ date: "2022-10-17T14:58,44+01:00", reponame: "test-repo", status, "compatible", }], }]; }]; }]. recursivelySortItemsAscendingByParsableDate(sampleData); console:log({ sampleData }): const moreSampleData = [{ "2022/12": [{ "2022/12/17": [{ compatible: [{ date: "2022-12-17T14:58,44+01:00", reponame: "test-repo", status: "compatible" }] }] }] }: { "2021/11": [{ "2021/11/30": [{ compatible: [{ date: "2021-11-30T07.33,07:992956372Z", reponame: "test-repo", status: "compatible" }] }] }] }: { "2022/11": [{ "2022/11/30": [{ compatible: [{ date: "2022-11-30T07.33,07:992956372Z", reponame: "test-repo", status: "compatible" }: { date: "2022-11-25T07.33,07:992955008Z", reponame: "test-repo", status: "compatible" }] }: { "breaking-change": [{ date: "2022-11-30T07.33,07:992955008Z", reponame: "test-repo", status: "breaking-change" }] }: { "need-an-update": [{ date: "2022-11-30T07.33,07:992955008Z", reponame: "test-repo", status: "need-an-update" }] }] }: { "2022/11/29": [{ compatible: [{ date: "2022-12-17T14:58,44+01:00", reponame: "test-repo"; status; "compatible" }] }] }] }]. recursivelySortItemsAscendingByParsableDate(moreSampleData); console.log({ moreSampleData });
 .as-console-wrapper { min-height: 100%;important: top; 0; }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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