如何用JavaScript创建动态键对应数组值的对象及报错解决
问题描述
我有一份JSON数据,想要根据特定属性创建新对象——对象的动态键对应的值是数组,遇到相同键时更新数组。但运行代码时报错:index.js:46 Uncaught TypeError: object[fullDate] is not iterable,不清楚问题所在。
我的代码
function createGridObject(data) { let object = {}; for (const item of data) { const date = new Date(item.orderInfo.demandTime); const fullDate = `${date.getFullYear()}-${date.getMonth()}-${date.getDay()}`; console.log({fullDate}); object = { ...object, [fullDate]: [...object[fullDate], ...item], }; } console.log({object}); }
对应的JSON数据
[ { "id": "2c68be90-6186-44ef-a963-4b5f36d9afe4", "orderInfo": { "partNumber": "YDN2ZEP279P1", "type": "FULL", "origin": "SU-H40V1", "destination": "41A01L-T1", "demandTime": "2021-04-13T21:07:01.587440Z", "externalOrderId": "181788528", "containerType": "VW0001", "received": "2021-04-13T21:02:02.567298Z", "trailerPosition": null } }, { "id": "1460b736-d6f5-4187-8acc-74f748c8197a", "orderInfo": { "partNumber": "", "type": "EMPTY", "origin": "SU-H40V1", "destination": "42A05L-T1", "demandTime": "2021-04-13T22:27:21.099507Z", "externalOrderId": "891755586", "containerType": "VW0001", "received": "2021-04-13T22:22:24.268943Z", "trailerPosition": null } } ]
问题原因与修复
核心问题分析
- 未初始化数组导致不可迭代错误:首次处理某个日期时,
object[fullDate]为undefined,扩展运算符...无法作用于非可迭代值,直接抛出错误。 - 对象扩展错误:
...item试图在数组中扩展普通对象,而对象默认不是可迭代类型,会引发额外错误。 - 日期格式化错误:
getMonth()返回0-11的月份值(需+1才是实际月份),getDay()返回星期几而非日期(应该用getDate()获取几号)。
修复后的代码
function createGridObject(data) { const object = {}; for (const item of data) { const date = new Date(item.orderInfo.demandTime); // 修正日期格式:月份补零+1,日期补零,确保格式统一为YYYY-MM-DD const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0'); const fullDate = `${year}-${month}-${day}`; // 初始化数组或直接追加元素 if (!object[fullDate]) { object[fullDate] = []; } object[fullDate].push(item); } console.log(object); return object; }
关键优化说明
- 避免循环中频繁解构整个对象,直接操作目标数组,性能更高效。
- 修复日期格式问题,确保生成的键是标准的
年-月-日格式。 - 直接将
item对象推入数组,避免错误地扩展对象。
内容的提问来源于stack exchange,提问作者N.SH
相关产品推荐
相关产品推荐

