按月对 json 数据数组进行分组

时间:2021-01-08 07:29:37

标签: javascript arrays json

我一直在尝试获取从数据库输出的 json 数据并创建一个新数组,该数组按月和年对数据进行分组。

问题是我的新数组没有以我需要的格式输出,所以我需要添加月份和年份,但无法首先使月份分组起作用。我认为这可能是正确的并解决了我的问题,但我需要帮助,因为数组令人困惑。

我有一个 codepen 演示 https://codepen.io/james182/pen/yLaqybP

var data = [
  { name: "First", timestampSent: "Wed, 25 Nov 2020 - 11:01 AM" },
  { name: "Second", timestampSent: "Wed, 25 Nov 2020 - 11:21 AM" },
  { name: "Third", timestampSent: "Thu, 26 Nov 2020 - 10:21 AM" },
  { name: "Fourth", timestampSent: "Fri, 27 Nov 2020 - 13:52 PM" },
  { name: "Fifth", timestampSent: "Tue, 24 Dec 2020 - 11:01 AM" },
  { name: "Sixth", timestampSent: "Wed, 25 Dec 2020 - 01:01 AM" }
];

// Clear console before running
console.clear();

var list = [];
for (i = 0; i < data.length; i++) {
  var dates = data[i].timestampSent.slice(5, 16);
  var mth = data[i].timestampSent.split(" ")[2];

  if (!list[mth]) {
    list[mth] = [];
  }

  list[mth].push({ name: data[i].name, date: data[i].timestampSent });

  console.log(mth);
}
console.log(JSON.stringify(list));
//console.log('list', list);

/*
outcome:
[{
'Nov': [
      {
        'name': 'First',
        'timestampSent': 'Wed, 25 Nov 2020 - 11:01 AM'
      },
      {
        'name': 'Second',
        'timestampSent': 'Wed, 25 Nov 2020 - 11:21 AM'
      },
      {
        'name': 'Third',
        'timestampSent': 'Thu, 26 Nov 2020 - 10:21 AM'
      },
      {
        'name': 'Fourth',
        'timestampSent': 'Fri, 27 Nov 2020 - 13:52 PM'
      }
    ],
    'Dec': [
      {
        'name': 'Fifth',
        'timestampSent': 'Tue, 24 Dec 2020 - 11:01 AM'
      },
      {
        'name': 'Sixth',
        'timestampSent': 'Wed, 25 Dec 2020 - 01:01 AM'
      }
    ]
  }]
*/
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

2 个答案:

答案 0 :(得分:2)

您的 list 不应是数组。由于您使用月份名称 ('Nov', 'Dec') 作为键,您应该使用一个对象。

var list = {};

答案 1 :(得分:0)

换行试试

list = [] 

list = {}

您将使用一个对象,而不是一个列表。 Try it here