Home > other >  How create an object with dynamic key and dynamic array value with javascript
How create an object with dynamic key and dynamic array value with javascript

Time:10-05

I have an json data and I wanna create a new object of it according a specific property of the json data; 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; But I got this error and I don't know what is my bug 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
        }
    },
]

CodePudding user response:

If object[fullDate] doesn't exist, [...object[fullDate], ___] is trying to use iterable spread on undefined. You can't do that. (People sometimes get confused, because you can use object property spread on undefined. But not iterable spread.)

Instead:

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

That way, if it's undefined, you'll spread [] instead.

Or use a conditional:

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