Currently, I have a JSON endpoint that returns data in the following format:
const tags = [
{
"name": "advertiser id",
"id": "12345",
"data_type": "output_type"
},
{
"name": "advertiser id",
"id": "345678",
"data_type": "output_type"
},
{
"name": "my name",
"id": "564563",
"data_type": "input_type"
},
]
The JSON contains multiple "data_types", with different forms. Currently, there are output_type **(2)**
and input_type **(1)**
, but this could vary greatly. To simplify the frontend, I am grouping this data.
Using Lodash:
const grouped = _.groupBy(tags, tag => tag.data_type);
In simplicity, using something similar to the above code snippet in Lodash, the data type will become a key, resulting in the desired JSON structure:
const tags = {
output_type: [{
"name": "advertiser id",
"id": "12345",
},
{
"name": "advertiser id",
"id": "345678",
}],
input_type: [
{
"name": "my name",
"id": "564563",
}],
}
An example of how I would implement this in TypeScript:
export interface TagDefinition {
name: string;
id: string;
}
export interface GroupedTags {
output_type: TagDefinition[];
input_type: TagDefinition[];
}
export interface TagsState {
tags: Tags[];
groupedTags: GroupedTags;
error?: Error;
}
My concern is about the flexibility of my current approach. Since the endpoint can return any data_type at any time, having predefined keys like 'output_type' and 'input_type' may not be dynamic enough. I'm exploring if there's a way, possibly using Generics, to make this more adaptable. Any suggestions on what this could look like?
edit I believe
might be the solution, but I'm not entirely certain.Dictionary<ToolDefinition[]>