// 对时间戳按日期进行分组 let moment = require('moment') let timestamp_array = [ 1645059333000, 1613523333000, 1297904133000, 1298076933000, 1582073733000, 1645318535000, 1647389537000 ] let result = {} for (let index in timestamp_array) { let timestamp = timestamp_array[index] let date = moment(timestamp).format("YYYY-MM-DD"); // let date = moment(timestamp).format("YYYY-MM"); // console.log(date); let date_split_array = date.split('-') // console.log(date_split_array); // 先判断年,之后判断月份 let year = date_split_array[0] let month = date_split_array[1] let judge_year = result.hasOwnProperty(year) if (judge_year == false) { result[year] = {} // result[year][date] = data judge_month(year, month,date) } else { // result[year][date] = data judge_month(year, month,date) } } console.log(result); function judge_month(year,month,date) { /* year: 字典中的年 month: */ let judge_month = result[year].hasOwnProperty(month) if(judge_month == false){ result[year][month] = {} result[year][month][date] = date }else{ result[year][month][date] = date } }
运行结果如下所示