Building Dynamic Properties in TypeScript

I have developed a data entry application that utilizes the DataGrid component from DevExpress (devextreme) to allow users to add and remove columns, excluding the key column. The column configuration and user data are both stored in an SQL database. Here is a sample of the user data format:

Key | ColumnName        | ColumnValue
-------------------------------------
1     Company             Apple
1     NumberOfEmployees   12345

The data is then pivoted before being sent to the grid:

Key | Company | NumberOfEmployees
---------------------------------
1     Apple     12345

When a user updates a row in the grid, the grid returns a data object containing properties for each column. I am using the column definition to try to match these properties, but the results are not as expected:

const userColumns: any[] = [
    {
        ColumnName: 'Company'
    }, {
        ColumnName: 'NumberOfEmployees'
    }
];

const returnedFromGridRow: Record<string, any> = {};
returnedFromGridRow.Company = 'Apple';
returnedFromGridRow.NumberOfEmployees = 12345;

let result: Record<string, any> = {};
const results: any = [];

userColumns.forEach(function (value) {
  let x: string = value.ColumnName;
  let y: string = returnedFromGridRow[x];
  
  result = {x:y};
  console.log(result);
  results.push(result);
});

Expected Output:

{ "Company" : "Apple" }
{ "NumberOfEmployees" : 12345 }

Actual Output:

{ "x" : "Apple" }
{ "x" : 12345 }

Playground

Answer №1

The method you are currently utilizing to generate the result object is not effective because it uses x as the key. To dynamically specify the key, modify the process of creating the dynamic object as shown below to achieve the desired outcome:

userColumns.forEach(function (value) {
  let x: string = value.ColumnName;
  let y: string = returnedFromGridRow[x];
  
  result[x]=y; // Here is the update
  console.log(result);
  results.push(result);
});

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

Conditional Return Types in a Typescript Function

There is a function that can return two different types, as shown below: function doSomething(obj: {a: string, b?: string}): string | number { if (obj.b) { return 'something' } return 1 } When the function is called with an object cont ...

Unable to transfer data through Ionic popover

I've encountered an issue when trying to pass data to my popover component, as the data doesn't seem to be sent successfully. Code HTML <div class="message" id="conversation" *ngFor="let message of messages.notes"> <ion-row class= ...

Are you familiar with Mozilla's guide on combining strings using a delimiter in Angular2+?

I found myself in need of concatenating multiple string arguments with a specific delimiter, so after searching online, I stumbled upon a helpful guide on Mozilla's website that taught me how to achieve this using the arguments object. function myCo ...

Will other functions in the file run if only a single function is imported?

The file bmiCalculator.ts contains the following code: import { isNotNumber } from './utils'; export default function calculateBmi(height: number, weight: number) { const bmi = weight / Math.pow(height / 100, 2); if (bmi < 18.5) { re ...

Is it possible for TypeScript to mandate abstract constructor parameters?

This specific function is designed to take a constructor that requires a string argument and then outputs an instance of the constructed value T: function create<T>(constructor: new(value: string) => T): T { return new constructor("Hello& ...

Using the index in Vue.js to locate a method within an HTML file

Currently, I am attempting to make use of the reference "index" located within <tr v-for="(note, index) in noteList" v-bind:key="index" in order to call shareToPublic(index). The method selectedID() allows for the selection of the ...

Despite setting the esModuleInterop flag, I am still encountering an error with default imports

My React project with TypeScript is causing some issues. In the main tsx file, the import React from 'react' line works fine. However, in my test file, I keep getting the TS1259 error. I suspect there might be a problem with my TS/Jest/Babel conf ...

Typescript is failing to perform type checking

I'm encountering an issue while trying to utilize TypeScript type checking with the following code snippet: abstract class Mammal { abstract breed(other: Mammal); } class Dog extends Mammal { breed(other: Dog) {} } class Cat extends Mammal { ...

What is the best way to generate a dynamic variable within an AngularJS view?

Can someone explain how to achieve a similar functionality in Angular? $scope.test = "foo"; $scope.foo = "bar"; and display it in the view like this <span>{{scope[test]}}</span> <!-- expecting $scope.foo to be displayed as "bar" --> ...

Issues with loading AddMarker on initial launch in Ionic 2

Can someone help me figure out what's causing the issue in my code? When I try to load a google map in my ionic 2 app, the marker doesn't show up the first time. It only appears when I reload the map for the second time or later. I also need ass ...

Seems like ngAfterViewInit isn't functioning properly, could it be an error on my end

After implementing my ngAfterViewInit function, I noticed that it is not behaving as expected. I have a hunch that something important may be missing in my code. ngOnInit() { this.dataService.getUsers().subscribe((users) => {this.users = users) ; ...

Creating instance methods in a TypeScript object can be accomplished by defining the methods within the object's class definition. When the object is

As a seasoned Java developer, I've recently been dabbling in TypeScript. Let me introduce you to my user object: export class User { id: string; name: string; email?: string; unit: string; street: string; postalcode: string; ...

Why is Axios not being successfully registered as a global variable in this particular Vue application?

Recently, I have been delving into building a Single Page Application using Vue 3, TypeScript, and tapping into The Movie Database (TMDB) API. One of the hurdles I faced was managing Axios instances across multiple components. Initially, I imported Axios ...

The C# private property is inaccessible during a TypeScript callback as it is not contained within the

I'm encountering an issue with TypeScript where the callback function is only returning _proto in the response's .data property when I set private properties in C# and instantiate an object filled with constructed properties. Strangely, if the pr ...

Efficiently incorporating multiple properties into one in Angular

Within my Angular service, I have defined variables in the following manner: export class MyService { someVariableA = 1; someParams = { someVariableB, otherVariable: this.someVariableA }; } In a component, I update 'someVariableA&a ...

Angular seed appears to experience a hiccup when the "Loading..." screen persists after the incorporation of a router-outlet

When working on a new Angular seed application using ng new, I encountered an issue where the application would get stuck at "Loading..." after adding the following to app.component.html: <router-outlet></router-outlet> In an attempt to resol ...

Execute supplementary build scripts during the angular build process

I've developed an Angular application that loads an iframe containing a basic html page (iframe.html) and a Vanilla JavaScript file (iframe.js). To facilitate this, I've placed these 2 files in the assets folder so that they are automatically cop ...

Using TypeScript with React Redux, encountering issue of property not being available in the Reducer from the ActionType

Currently, I am learning how to implement a Reducer in Redux while using React with TypeScript. I have encountered an issue that I need help with. Below are the action types that I am working with: import { LoginResponseInterface } from "../../interfaces ...

How is it possible that this is not causing a syntax or compile-time error?

Oops! I made a mistake and typed : instead of = on line 2 of this code snippet. Why does Typescript allow this error? Isn't colon supposed to indicate a known Type for a property declaration? I'm pretty sure there's a reason encoded in the ...

A guide on creating a function that can detect if an object is not iterable and then throw an error

Exploration Uncomfortable type definition at the library: declare type Extension = { extension: Extension; } | readonly Extension[]; Type-validation function export function isIterable(x: any): x is Iterable<unknown> { return Symbol.iterator ...