如何使用javascript创建具有动态键和动态数组值的对象



我有一个json数据,我想根据json数据的特定属性创建一个新的对象;这个动态键的值应该是一个数组,如果在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});
}
[
{
"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]不存在,则[...object[fullDate], ___]尝试在undefined上使用可迭代排列。你不能那样做。(人们有时会感到困惑,因为可以undefined上使用对象属性排列。但不能使用可迭代排列。(

相反:

object = {
...object,
[fullDate]: [...object[fullDate] ?? [], ...item],
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^
};

这样,如果它是undefined,您将传播[]

或者使用条件:

object = {
...object,
[fullDate]: object[fullDate] ? [...object[fullDate], ...item] : [...item],
};

最新更新