I have an application with Angular 2.x written in typescript where I need to create a JSON Structure dynamically based on User Interactions with the UI. The JSON Structure consists of key:value parameters and arrays. This JSON Structure is then sent to an API as HTTP Parameter.
A simplified example for the JSON structure:
{
'key_1': 'param_1',
'key_2: 'param_2',
'array_key_1': [
{
'key_1_1': 'value_1_1',
'key_1_2': 'value_1_2
},
{
'key_2_1': 'value_2_1',
'key_2_2': 'value_2_2'
}
],
'array_key_2': [
{
'key_1_1': 'value_1_1',
'key_1_2': 'value_1_2,
'someArray': [...]
},
{
'key_2_1': 'value_2_1',
'key_2_2': 'value_2_2'
'someArray': [..]
}
]
}
This JSON Structure is used as a query for a Database.
Current Implementation
Initially I declare a public sqlJSON: Object = {}
in the component and use ngOnInit()
LifeCycleHook to initialize the empty arrays (this is needed because if not initialized, Angular will not recognize the array when an entry is pushed into it).
I use the ngOnChanges
LifeCycleHook to reset the JSON Structure if the user changes the to another topic of interest. For instance, sqlJSON['array_key_1] = []
and so on.
Query
Is there a better way to use create such JSON Structures? For instance can one use localStorage
for the same keeping in mind that the JSON might turn out to be very large if the user interacts with the UI alot? Also are there any memory constraints while storing such JSON Structures in localStorage
.
It is also worth informing that since the Backend Requirements keep changing, the above mentioned JSON Structure needs to keep adding/removing new key:value parameters.
Can an interface
be used for the building this JSON? I think since parameters keep added/removed an interface
would be more adaptable.