javascript - Javascript中带有日期键的动态多维数组
问题描述
如何按键和子数组循环新创建的动态数组。
var days = new Array();
$.each(json_object, function(r, row) {
var online_date = new Date(row.date_field * 1000);
var day_key = '' + online_date.getFullYear() + '' + (online_date.getMonth()+1) + '' + online_date.getDate() + '';
if(!days[day_key]) {
days[day_key] = [];
}
days[day_key][r] = row;
});
console.log('days.length');
console.log(Object.keys(days).length);
// 3 days woth of data..
// 20, 30 records each day...
for(var d = 0; d < Object.keys(days).length; d++) {
var day = days[d];
// day is undefined
console.log(day);
// I want KEY for 'day_key' and the data rows...
}
我正在使用 jQuery 或基本 JS。如果我对数组进行过滤或排序,我会丢失我的密钥,因为我想每天绘制图表。
谢谢。
解决方案
您应该声明days
为对象,而不是数组:
var days = {};
$.each(json_object, function(r, row) {
var online_date = new Date(row.date_field * 1000);
var day_key = '' + online_date.getFullYear() + '' + (online_date.getMonth()+1) + '' + online_date.getDate() + '';
if(!days[day_key]) {
days[day_key] = []; // Define an array for the rows to go into
}
days[day_key].push(row); // Add the row to the array
});
console.log('days.length');
console.log(Object.keys(days).length);
// 3 days worth of data..
// 20, 30 records each day...
Object.keys(days).forEach(day => {
console.log(day);
// I want KEY for 'day_key' and the data rows...
// The array of rows for the day are available
console.log(`Rows for ${day}: `,days[day])
})
我认为这会做你想要的
推荐阅读
- docker - 使用目录外的环境文件在构建期间使用 docker-compose 提供参数
- php - Yii2 - gridview 自定义操作按钮的 403 错误
- django - 是否可以使用基于类的通用 ListView 在单个模板中同时过滤和排序?如果是,如何?
- database - 一个领域,两个目的
- typescript - 如何正确使用模块扩充来扩展现有的 TypeScript 库?
- keras - 如何在keras中显示估计排名?
- c# - 如何在 C# 中调用自定义 url 协议?
- php - Yii2 文件验证总是显示为空
- php - 如何在 Laravel 5.8 中写这个(左连接和 on)?
- azure - 如何在 Kudu(Azure) 的 java 密钥库中导入受信任的证书或密钥库