简体   繁体   English

按月分组 json 数据数组

[英]Group json data array by month

I have been trying to take the json data outputted from the database and create an new array that groups the data by month and year.我一直在尝试获取从数据库输出的 json 数据,并创建一个按月和年对数据进行分组的新数组。

The problem is my new array doesn't output in the format that i need so i need to add the month and year but can't get the month grouping to work first.问题是我的新数组没有 output 在我需要的格式,所以我需要添加月份和年份,但不能让月份分组首先工作。 I think that might be right and resolve my issue, but I need help as arrays are confusing.我认为这可能是正确的并解决了我的问题,但我需要帮助,因为 arrays 令人困惑。

I have a codepen demo https://codepen.io/james182/pen/yLaqybP我有一个 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>

Your list should not be an array.你的list不应该是一个数组。 Since you are using the month name ('Nov', 'Dec') as keys you should use an object.由于您使用月份名称('Nov'、'Dec')作为键,您应该使用 object。

var list = {};

try change the line尝试换行

list = [] 

to

list = {}

You will be using an object, not a list.您将使用 object,而不是列表。 Try it here在这里试试

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

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