Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert a nested object into an array of group options (React hooks)

I am a new dev and I am having trouble converting this nested object into an array of options with categories.

Response from API call:

{
    "category1": [
    {
        "categoryCode": "category1",
        "categoryLabel": "Vehicles",
        "code": "AAA",
        "label": "Car a"
    },
    {
        "categoryCode": "category1",
        "categoryLabel": "Vehicles",
        "code": "BBB",
        "label": "Car b"
    }
    ],
    "category2": [
    {
        "categoryCode": "category2",
        "categoryLabel": "Ship",
        "code": "CCC",
        "label": "Ship a"
    },
    {
        "categoryCode": "category2",
        "categoryLabel": "Ship",
        "code": "DDD",
        "label": "Ship b"
    },
    {
        "categoryCode": "category2",
        "categoryLabel": "Ship",
        "code": "EEE",
        "label": "Ship c"
    },
    ],
}

The output should be this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

options = [
    {
label: "Vehicles",
options: [
            { label: "Car a", value: "AAA"
            },
            { label: "Car b", value: "BBB"
            }
        ]
    },
    {
label: "Ship",
options: [
            { label: "Ship a", value: "CCC"
            },
            { label: "Ship b", value: "DDD"
            },
            { label: "Ship c", value: "EEE"
            },
        ]
    },
];

>Solution :

You could get the values of the object and map with getting some values from the first object of each group.

const
    data = { category1: [{ categoryCode: "category1", categoryLabel: "Vehicles", code: "AAA", label: "Car a" }, { categoryCode: "category1", categoryLabel: "Vehicles", code: "BBB", label: "Car b" }], category2: [{ categoryCode: "category2", categoryLabel: "Ship", code: "CCC", label: "Ship a" }, { categoryCode: "category2", categoryLabel: "Ship", code: "DDD", label: "Ship b" }, { categoryCode: "category2", categoryLabel: "Ship", code: "EEE", label: "Ship c" }] },
    result = Object
        .values(data)
        .map(array => ({
            label: array[0].categoryLabel,
            options: array.map(({ label, code: value }) => ({ label, value }))
        }));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading