Inside my API response of data, I'm trying to loop over an array of objects in items.
I need to format each value inside the object. Each key in the items list of objects corresponds to a format type in my header key. I also have a getFormat function to help format the values
My question is how would I do this given the structure I have?
// Data
const data = {
header: {
date: {
feature: "Date",
format: "date",
},
description: {
feature: "Description",
format: "text",
},
salary: {
feature: "Salary",
format: "currency",
},
score: {
feature: "Score",
format: "float",
},
useage: {
feature: "Useage",
format: "percentage",
},
},
items: [
{
date: "2021-02-08",
description: "Light",
salary: "50000",
score: 20,
useage: 20,
},
{
date: "2021-02-08",
description: "Heavy",
salary: "60000",
score: 50.235,
useage: 30,
}
],
};
// format helper
export const getFormat = (value: any, format: FormatProp) => {
let options: Intl.NumberFormatOptions;
switch (format) {
case "currency":
options = { currency: "USD", style: "currency" };
break;
case "percentage":
options = { style: "percent", maximumFractionDigits: 2 };
break;
case "float":
options = { maximumFractionDigits: 2, minimumFractionDigits: 2 };
break;
case "text":
return value;
case "date":
return value;
default:
throw Error("Wrong Format!");
}
return Intl.NumberFormat("en-US", options).format(value);
};
export type FormatProp =
| "currency"
| "percentage"
| "float"
| "text"
| "date";
Desired Output
[{
date: "2021-02-08",
description: "Light",
salary: "$50,000.00",
score: "20.00",
useage: "20%",
},
{
date: "2021-02-08",
description: "Heavy",
salary: "$60,000",
score: "50.24",
useage: "30%",
}]