Adding to object properties in Typescript

My goal is to dynamically generate an object:

newData = {
    column1: "",
    column2: "",
    column3: "",
    ...
    columnN: ""
}

The column names are derived from another array of objects called tableColumns, which acts as a global variable:

tableColumns = [
    {headerName: "column1", field: "c1", editable: false},
    {headerName: "column2", field: "c2", editable: false},
    {headerName: "column3", field: "c3", editable: false},
    {headerName: "column4", field: "c4", editable: false}
]

I am looking for a way to dynamically create newData without manually specifying the columns by looping through this.tableColumns.

Answer №1

Go through each element in the tableColumns array and assign the value of headerName as a key in the newData object:

var tableColumns = [
    {headerName: "column1", field: "c1", editable: false},
    {headerName: "column2", field: "c2", editable: false},
    {headerName: "column3", field: "c3", editable: false},
    {headerName: "column4", field: "c4", editable: false}
];

var newData = {};

tableColumns.forEach((col)=>{
  newData[col.headerName] = '';
});

console.log(newData);

Answer №2

Iterate through each item in your collection and dynamically set attributes based on the values in your headerName column

const tableDetails = [
    {headerName: "property1", field: "prop1", editable: false},
    {headerName: "property2", field: "prop2", editable: false},
    {headerName: "property3", field: "prop3", editable: false},
    {headerName: "property4", field: "prop4", editable: false}
];

const results = {};

tableDetails.forEach(item => {
  results[item.headerName] = item.field;
});

console.log(results);

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

Excessive wait times during the construction of a moderately sized application (over 2 minutes) using TypeScript and loaders like Vue-Loader and TS-Loader

I'm currently utilizing Nuxt 2 with TypeScript and the most up-to-date dependency versions available. Even though my app is of medium size, the compilation time seems excessively slow. Here are my PC specs: Ryzen 7 2700X (8 Cores/16 Threads) 16 GB D ...

The total height of the document's body in jQuery is not equal to the sum of the viewport height and the window's scroll top position at the bottom of the document

Why does the document height appear smaller than the window scroll top value plus the viewport height when I reach the end of the document? Shouldn't they be equal? I've been struggling with this issue for hours and can't seem to figure it o ...

Exploring ngModel components with a specified class

In my HTML code, I've assigned many elements with ngModel defined as ng-model = "object.[something]". For example: <div class="form-group row" ng-model="object.askUser"> I use this method to keep my purpose clear for these elements. My questi ...

Displaying svg files conditionally in a react native application

I have developed an app specifically for trading dogs. Each dog breed in my app is associated with its own unique svg file, which are all stored in the assets folder (approximately 150 svg files in total). When retrieving post data from the backend, I re ...

I'm having trouble importing an image into my typescript file as it keeps showing a "module not found" error message. Can anyone

I am new to working with TypeScript and I have encountered an issue when trying to import an image from my assets folder. Despite having the image stored in a designated folder, Visual Studio Code notifies me that it cannot find the module. Here is the er ...

Selecting middleware to be executed based on Express JS request parameters

Can someone please advise me on how to select between two distinct middleware functions, based on the request for a specific endpoint? It may involve something along these lines: router.post("/findAvailableAgents", chooseMiddleware(middleware1, ...

Guide on associating user IDs with user objects

I am currently working on adding a "pin this profile" functionality to my website. I have successfully gathered an array of user IDs for the profiles I want to pin, but I am facing difficulties with pushing these IDs to the top of the list of profiles. My ...

The continuous re-rendering is being triggered by the Async/Await Function

I am facing an issue with fetching data from the backend using axios. The function is returning a Promise and each time I call it, my component keeps rendering continuously. Below is the code snippet: import { useState } from "react"; import Ax ...

Navigate to the AngularJS documentation and locate the section on monitoring data changes after a dropdown selection

Just starting out with AngularJS and Stack Overflow, so I hope I am asking this question correctly. I am working on a single-page application with editable text inputs. Two select drop-downs are used to control which data is displayed - one for time perio ...

Looking to add some color to the tags within an XML document that is being shown in a textarea?

Currently, I am attempting to add color to the tags within an XML string that is being displayed in a textarea on an HTML page. For example, let's say I have an XML string stored in a variable called 'xmldata'. The HTML textarea tag looks ...

Steps for rearranging the order of CSS grid layout

Could you assist me in implementing a grid layout that fulfills these specific criteria? I'm unsure of how to proceed, so any guidance would be greatly appreciated. https://i.sstatic.net/vBtXc.png When there are more than 9 items, the current layout ...

Guide on merging non-modular JavaScript files into a single file with webpack

I am trying to bundle a non-modular JS file that uses jQuery and registers a method on $.fn. This JS must be placed behind jQuery after bundling. Here is an example of the structure of this JS file: (function($){ $.fn.splitPane = ... }(JQuery) If y ...

Retrieving an individual instance of a component

Is there a way to access a specific instance of a component within an app that uses it multiple times in other components? Currently, when I use the query command "fixture.debugElement.query(By.directive(ComponentName)).componentInstance;", it only recogni ...

What could be causing the npm server error in my Vue.js application?

After recently setting up Node.js and Vue.js, I decided to dive into my first project on Vue titled test. As part of the process, I attempted to configure the server using the command: npm run server However, I encountered the following error message: C ...

Is there a risk of overloading the server and browser by making constant AJAX calls at regular intervals?

I am in the process of creating a website that requires notifications. I want to use AJAX to continuously check for updates in my database where notifications are stored at regular intervals. My concern is, with multiple users all accessing the AJAX call ...

Angular Authentication Functionality

I need to create a loggedIn method in the AuthService. This method should return a boolean indicating the user's status. It will be used for the CanActivate method. Here is a snippet of code from the AuthService: login(email: string, password: string) ...

The JavaScript code is not being executed, as the address bar displays the function name instead

In my project, I have created numerous "js-classes" with various functions spread across different files. Unfortunately, the codebase is too large to share entirely. However, towards the end of the project, I encountered a bug where a specific function wa ...

Converting HTML to PDF with rtl support using the JavaScript library jsPDF

I'm attempting to convert HTML to PDF using jsPDF in an Angular 5 project. Below is the code I have so far: import * as jsPDF from "jspdf"; . . . htmlToPdf(){ var doc=new jsPDF(); var specialElementHandlers = { '#content' : function ...

The process of loading and saving extensive data to the local storage of a user's Firefox browser involves extensive reading and writing operations

Our team has developed a sophisticated HTML5 offline application that houses a substantial amount of data, totaling tens of megabytes. We are looking for a way to allow users to save and retrieve copies of this data on their disk. While we have made some ...

The issue arises when DataTable fails to retrieve the ID element following a page transition

I am facing an issue with making ajax calls on focus for each text input. I am able to do it on the first page, during document ready event. However, when I navigate to another page, JavaScript is unable to parse the inputs as they were not created during ...