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

Setting the default time zone to UTC for Material UI date and time picker

Looking to implement a dialog in React with Material UI for users to input start and end date/time. The goal is to have the default start set to the beginning of the current day and the default end set to the end of the current day (UTC). However, I'm ...

Module fails to load in the proper sequence

As a .NET developer who is relatively new to modern client-side web applications, I am currently working on developing an Angular2 charting application using Chart.js. The modules are being loaded with SystemJS. Below is the content of my systemjs.config. ...

Guide to displaying a table enclosed in a div based on a selected value in a select dropdown?

I am attempting to retrieve the table options using the select question-picker: Here is what I have tried: $(document).ready(function() { var question_container = $('.question-picker option[value="1"]').parent(); console.log(question_cont ...

Angular is encountering a circular dependency while trying to access a property called 'lineno' that does not actually exist within the module exports

I am working on an Angular project and using the Vex template. My project utilizes Angular 9 and Node.js v15.2.0. Every time I run the project with the command ng serve -o, it displays a warning message. https://i.stack.imgur.com/8O9c1.png What could b ...

Transmit both image and JSON data in a single response using Node.js and Express

I'm in the process of building a web API using Node.js and Express and my goal is to send back both an image and JSON data in a single response. I came across a solution that involves specifying headers at , but I'm looking for a way to achieve t ...

Guide to simulate the store.pipe method in an Angular component during unit testing

Just starting out with Angular and I'm trying to write unit tests for a component that retrieves data from the store. I've mocked both the service files and the store itself, but when running the test, I keep encountering the following error. Eve ...

How do you transfer byte[] data using a DTO in Java Spring?

I am currently facing an issue with my server-side application. The problem arises when attempting to convert a Blob to an Excel file on the front-end, specifically when the byte[] is sent within a DTO. When sending a POST request from the back-end (sprin ...

the append function combines existing data with new data

After retrieving data through ajax, I am facing a challenge in displaying it within a UI popup: [{"BadgeImage":"http:\/\/localhost:8666\/web1\/profile\/images\/badge image 2\/1.png"}, {"BadgeImage":"http:\/\/lo ...

Creating an array of custom objects in JavaScript.Initializing custom objects in an

Is there a proper way to prevent the error "Cannot read property 'length' of undefined" when initializing an array of custom objects in javascript? situation export class MyClass implements OnInit { myArray: MyObject[]; } example <div ...

Download files from Firebase storage to a user's device

I have a variety of files such as images, videos, and audio stored in my firebase storage. My goal is to provide users with the ability to download these files to their computers by clicking on a download button. After reviewing the firebase documentation ...

Steps to creating a popup within an HTML page from another HTML page

I recently started learning JavaScript. I have a link on my homepage that directs to another HTML page, but I would like it to show as a popup on the homepage with responsiveness and some stylish design elements such as a folded corner. Is there a way to a ...

Determine the current whereabouts and actions of the specified user

I am in the process of developing a command for my Discord JS bot that, when activated, will fetch the current game (or status if no game) of the user mentioned in the command. Subsequently, the bot will send a message stating Mentioned User has been playi ...

Extending a Sub-Object in JavaScript

I'm attempting to include new attributes to the sub-object within object1. However, I am facing issues with it being overwritten. const object1 = { a: 1, b: 2, c: 3, sub: { e: 1, f: 2 } }; const object2 = Object.assign({ j: 4, ...

initiate a page refresh upon selecting a particular checkbox

So I've got this code that saves around 30 checkbox selections to local storage, which is working fine. Then there's this separate checkbox below, when checked it automatically reloads the page: <input type="checkbox" id="autoload" class="aut ...

The table gets disrupted by the presence of an Angular child component

I am facing an issue with my Angular component when trying to use it within a table using ngFor. This is how my table is structured: <table class="table table-stripped"> <thead> <th style="width: 30%;">Network< ...

What is the best way to conceal the button?

I'm working on a program that involves flipping cards and creating new ones using three components: App, CardEditor, and CardViewer. Within the CardEditor component, I am trying to implement a function that hides the button leading to CardViewer until ...

Errors encountered when using Puppeteer on Kubernetes: "Detached navigation frame" and "Attempting to access main frame too soon"

I have been attempting to execute a nodejs based Docker container on a k8s cluster, but I am encountering persistent errors: Navigation frame was detached Requesting main frame too early In an effort to resolve this issue, I have condensed the code to ...

Angular 5 update causing 'NgModule not found' error

After attempting to upgrade my app to Angular 5, I encountered a series of bugs. Among them, there is one persistent issue that has me stumped. An uncaught error has surfaced: 'Unexpected value HttpClient imported by the module AppModuleShared. Ple ...

What is the process for deactivating touch gesture recognition in a particular view within an IONIC3 application?

I am looking to prevent all touch gestures on certain views within my app. Users should only be able to interact with the app using an external keyboard while in these views. I have reviewed the Ionic Docs but couldn't find clear instructions, I onl ...

AngularJS allows a function to return an array value, which can be displayed in separate blocks on

Building a program that involves working with an AngularJS array. I need to showcase the elements of the AngularJS array, returned by a function, in an organized manner. Each element should be displayed correspondingly - for example, 'first' cont ...