I need to take serviceType from my array and convert it to the following layout keeping only the unique values.
[
{
"Label": "Cars Now"
"Value": "Cars Now"
},
{
"Label": "Vans Now"
"Value": "Vans Now"
},
]
I’ve got the unique values below, but I can’t work out how to convert it to the layout I need.
const inputArray = [
{
"serviceType": "Cars Now",
"applictionType": "Direct",
"wheelType": "4x4"
},
{
"serviceType": "Cars Now",
"applictionType": "web",
"wheelType": "2x4"
},
,
{
"serviceType": "Vans Now",
"applictionType": "Direct",
"wheelType": "2x4"
}
]
let tempArr = inputArray.map(row => row.serviceType) // map extracts the serviceType
.filter(service => service); // filter removes any undefined/empty values
newServiceSet = [...new Set(tempArr)] // only keeps unique values
console.log(newServiceSet)
>Solution :
Turn the Set of serviceTypes into an an array of strings, then map to turn each string into an object. You also need to filter out the empty space in the array.
const inputArray = [
{
"serviceType": "Cars Now",
"applictionType": "Direct",
"wheelType": "4x4"
},
{
"serviceType": "Cars Now",
"applictionType": "web",
"wheelType": "2x4"
},
,
{
"serviceType": "Vans Now",
"applictionType": "Direct",
"wheelType": "2x4"
}
];
const serviceTypes = new Set(inputArray.filter(Boolean).map(({ serviceType }) => serviceType));
const output = [...serviceTypes].map(label => ({ label, value: label }));
console.log(output);