Utilizing a string as an argument in a function and dynamically assigning it as a key name in object.assign

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.

Answer №1

One way to incorporate a computed property into an object literal is by utilizing a variable:

let keyName: string = 'itemName';
let objExample = {[keyName]: 'Item Value'}; // this will result in { 'itemName': 'Item Value'} when executed

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am attempting to retrieve JSON data in JavaScript but am seeing a null response in the action class

Having an issue with JSON data being sent through AJAX from the client side. The data is showing as null inside my action class. Here is the JSON string: {"data":[{"id":"","col":1,"row":1,"size_x":1,"size_y":1}, {"id":"","col":1,"row":2,"size_x" ...

Is there a way to prevent Express.js from triggering a file download in the browser?

I am attempting to preview a Word document file in the browser using an iframe: <iframe style="float:right;" src="/ViewerJS/#../demo/ohm2013.odp" width='400' height='300' allowfullscreen webkitallowfullscreen></iframe> (Fo ...

Experiencing difficulties with NPM installation

Screenshot of my terminal in VSCode Despite attempting to uninstall and reinstall node and clearing the cache, I am still unable to resolve this issue. Any suggestions? If it's relevant, I am using Windows 10. ...

Closing Accordions Automatically

Hello everyone! I'm currently working on a NextJS project and facing an issue with my dynamic accordion component. I'm using typescript, and the problem lies in only one accordion being able to open at a time. How can I ensure that only the spec ...

Can you please tell me the event that is triggered when an option is unselected in Vue.Drag

I am trying to figure out the event for selecting an item since I already know about the "choose" event. However, I am uncertain about what to use for un-selecting an item. In my particular case, I am unable to utilize the @end event. <draggable :list= ...

The condition for the result of a jQuery $.post call

I've customized this code obtained from the jQuery website by incorporating a condition into it. However, regardless of the outcome, it consistently enters the first 'if' statement. How can I ensure that my condition is functioning correctly ...

Incorporating an event listener for 'storage' in jQuery using JavaScript

Can anyone tell me how to achieve the same functionality as javascript addEventListener in JQuery? I have been attempting to use it with .bind(), but it seems not to recognize the "storage" keyword. When I tried using 'e' within this context, it ...

Having trouble deploying Firebase Cloud function following the migration to Typescript

After following the steps outlined in the firebase documentation to convert my cloud functions project to TypeScript (see https://firebase.google.com/docs/functions/typescript), I encountered an error when attempting to deploy using 'firebase deploy - ...

node js retrieves information from the request body

Hey there! I'm diving into the world of Node.js and JavaScript, but I've hit a roadblock. I'm trying to fetch data from a URL using node-fetch, then parse it as JSON. However, I keep running into the issue of getting 'undefined' in ...

What is the significance of the A tag when parsing a URL?

So, I encountered a problem that involved parsing a URL to extract the hostname and pathname, then comparing the extracted pathname with a string. If you need help with this issue, check out this post: How do I parse a URL into hostname and path in javasc ...

Selenium unfortunately does not fully function with JavascriptExecutor

When I attempt to input text using JavascriptExecutor, the code snippet below is what I use: private void inputWorkDescription(WebDriver driver, int rawNumber) throws IOException, GeneralSecurityException { if (!getWorkDescriptionFromSheets(rawNum ...

Invoking a function that is declared in a fetch request from an external source beyond the confines of the fetch itself

I am currently struggling with calling a function that is defined inside an API Fetch response function. My code sends an API fetch request to the GitHub API to retrieve a repository tree in JSON format. The problem arises when I try to call a function def ...

Trouble obtaining AJAX result using onClick event

As a newbie to AJAX, I am still trying to grasp the concept. My task involves using an AJAX call to extract specified information from an XML file. Even after carefully parsing all tag elements into my JavaScript code, I encounter a problem when attempting ...

Navigational module and wildcard for routes not located

I have my routing configuration structured as follows: app-routing const routes: Routes = [ { path: 'login', loadChildren: 'app/modules/auth/auth.module#AuthModule' }, { path: '', redirectTo: 'dash ...

Retrieve unique values based on two or more criteria from an array in TypeScript

Presented here is an array. https://i.stack.imgur.com/zHXim.png The desired pattern is: https://i.stack.imgur.com/EGUiM.png I am interested in retrieving unique "CityRef" and "City". Subsequently, locating all items associated with them. ...

Tips for incorporating a favicon in a React application

Having trouble adding a favicon to my React application. I followed the instructions in this post, but it's not working for me. I placed the favicon.ico file inside the public folder where index.html resides. This is how my directory structure looks ...

What is the best way to call another "put" action method within the same controller file?

My project revolves around the interaction of two models - User and Request. A User can create a food delivery Request, attaching tokens as rewards. Another User can then help deliver the request and claim the tokens. Within the same controller.js file, I ...

javascript loop that runs on every second element only

After completing an ajax query, the following JavaScript code is executed. All of my images are named "pic". <script type="text/javascript> function done() { var e = document.getElementsByName("pic"); alert(e.length); for (var i = 0; ...

JavaScript with dropdown menus

Currently, I am in the process of implementing a JavaScript code snippet that will be triggered when a checkbox is checked. Once the checkbox is checked, the form should display two additional select boxes. My attempt at coding this functionality was not ...

Is there a way to easily toggle a Material Checkbox in Angular with just one click?

Issue with Checkbox Functionality: In a Material Dialog Component, I have implemented several Material Checkboxes to serve as column filters for a table: <h1 mat-dialog-title>Filter</h1> <div mat-dialog-content> <ng-container *ng ...