Within my Angular 5 app written in TypeScript, I have a method in a service that requires two arguments: an event object and a string serving as the key for an object stored in the browser's web storage.
This method is responsible for assigning a new object to the browser's web storage while combining it with another object. Here's the code snippet:
setPaginationObject(event: any, list: string) {
let sitePagination = JSON.parse(sessionStorage.getItem('sitePagination')) || {};
sitePagination = Object.assign(sitePagination, {list: event});
sessionStorage.setItem('sitePagination', JSON.stringify(sitePagination));
}
Here's an example of how I would call this method within a component:
public onPaginateChange(event: any): void {
this.paginationService.setPaginationObject(event, 'usersList');
}
My issue arises from needing the argument to be assigned dynamically as the key name in the Object.assign
function, instead of using a static label like "list". How can I achieve this?
I initially attempted something like this:
sitePagination = Object.assign(sitePagination, {`${list}`: event});
but unfortunately, that approach did not work. Alternatively, I considered adjusting the method signature to pre-format the object in the component rather than the service:
this.paginationService.setPaginationObject({'usersList': event});
In the service file:
setPaginationObject(obj: any) {
let sitePagination = JSON.parse(sessionStorage.getItem('sitePagination')) || {};
sitePagination = Object.assign(sitePagination, obj);
sessionStorage.setItem('sitePagination', JSON.stringify(sitePagination));
}
While the above solution seems acceptable, I am still curious about dynamically setting the key name in the Object.assign
function.
Thank you in advance for your assistance, and apologies if my wording is unclear. Feel free to ask me to clarify further if needed.