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:
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; }