简体   繁体   English

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

[英]How create an object with dynamic key and dynamic array value with javascript

I have an json data and I wanna create a new object of it according a specific property of the json data;我有一个 json 数据,我想根据 json 数据的特定属性创建一个新的 object; The value of this dynamic key should be an array and I need to update this array if a similar key founded in json data;这个动态键的值应该是一个数组,如果在 json 数据中找到类似的键,我需要更新这个数组; But I got this error and I don't know what is my bug index.js:46 Uncaught TypeError: object[fullDate] is not iterable但是我得到了这个错误,我不知道我的错误是什么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
        }
    },
]

If object[fullDate] doesn't exist, [...object[fullDate], ___] is trying to use iterable spread on undefined .如果object[fullDate]不存在,则[...object[fullDate], ___]会尝试在undefined上使用可迭代展开。 You can't do that.你不能那样做。 (People sometimes get confused, because you can use object property spread on undefined . But not iterable spread.) (人们有时会感到困惑,因为您可以undefined上使用 object 属性传播。但不能迭代传播。)

Instead:反而:

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

That way, if it's undefined , you'll spread [] instead.这样,如果它是undefined ,您将改为传播[]

Or use a conditional:或者使用条件:

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

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

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