What is the best way to retrieve the value of templated objects in TypeScript that refer to another object?

As a novice in typescript, I am seeking guidance on the most efficient method to accomplish this task using typescript:

I have a map object that serves as a field mapping tool for combining two objects: source and target.

The map object remains unalterable, with the format of "${source}.field1" always being a string.


source = { "field1" : 10, "field3" : 30}
target = { "field2" : 20, "field4" : 40}

map = {
      "JuncField1":"${source}.field1",
      "JuncField2":"${target}.field2"
}

The primary objective is to generate a new object, based on the aforementioned mapping. What approach would be the most effective?

{ "JuncField1" : 10, "JuncField2" : 20}

Answer №1

The sample you provided is very similar to what you are looking for.

let sourceData = { "fieldA" : 15, "fieldC" : 35}
let targetData = { "fieldB" : 25, "fieldD" : 45}

let mapping = {
      "CustomField1": sourceData.fieldA,
      "CustomField2": targetData.fieldB
}

Answer №2

To extract the corresponding keys from both the source and target objects, you can iterate through each object and create a new map object with the matching key-value pairs.

const resultMap = {};
for (let prop in targetObject) {
  resultMap[prop] = { ["target-" + prop]: targetObject[prop], ["source-" + prop]: sourceObject[prop] };
}

// The resultMap will look like this
/*
{
 "field1":{"target-field1":10,"source-field1":20},
 "field2":{"target-field2":20,"source-field2":30}
}
*/

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

Decipher intricate JSON data using Typescript

When a request receives a response, it is delivered in JSON format. The specific structure of the JSON data is as follows: { "32": { "docKey": "32", "outletId": 32, "mdngOutlet": { "outletBasic": { "outletId": 32, } ...

Error message: TscToolPath is missing in the Microsoft.TypeScript.targets file following the installation of Visual Studio 2015 update 3

Encountering an error in Visual Studio 2015 after updating to version 3 and using TypeScript 2.0. Error Invalid command line switch for "tsc.exe". Value cannot be null. Parameter name: path1 ProjectTest C:\Program Files (x86)\MSBuild&bso ...

The angular build prod function was expecting 2 arguments, but only 1 argument was provided

When I serve my Angular app normally, everything works fine. But when I try to serve it in production mode, I encounter this error that is leaving me quite perplexed. //error on build: Expected 2 arguments, but got 1. <ion-col class="ion-no-paddin ...

Setting up the cypress-grep plugin version 3.1.0 on Cypress v11.01: A Step-by-Step Guide

Cypress Version 11.0.1 Node Version 16.16.0 Package Manager Yarn version 1.22.19 Operating System Windows 10 Pro Version 21H2 To practice using the Cypress grep plugin, I have set up a test project called cypress_grep_test_project. I have modified som ...

Angular can display text on hover based on the state shown in a <td> element

Working on an Angular 7 project, I have a <td> element where I display different colors to indicate the status of a task: Red - Indicates 'Delayed' Orange - Indicates 'In progress' Grey - Indicates 'Rejected' Cu ...

Utilizing PrimeNG dropdowns within various p-tree nodes: Distinguishing between selected choices

I am working with a PrimeNg p-tree component <p-tree [value]="treeNodes" selectionMode="single" [(selection)]="selectedNode"></p-tree> The treeNodes are defined using ng-templates, with one template looking li ...

Is a shallow copy created by spreading?

According to the example provided in the documentation, let first:number[] = [1, 2]; let second:number[] = [3, 4]; let both_plus:number[] = [0, ...first, ...second, 5]; console.log(`both_plus is ${both_plus}`); first[0] = 20; console.log(`first is ${firs ...

Click on the button to generate a PDF report using Internet Explorer 11

After encountering some challenges with printing a PDF report specifically on IE 11, I am reaching out for help. The code snippet below works perfectly in Chrome, but when it comes to IE 11, everything falls apart. Just to provide some context, I am develo ...

Tailored component properties for React applications

I am currently working on configuring discriminative component props. Check out my code snippet below: import React, { ReactNode } from 'react' type SelectionModalProps<T> = ( | { multiSelect: true onSubmit: (data: T[]) => ...

Enumerations in Typescript act as interfaces

Utilizing a TypeScript to proto file generator library (ts-protoc-gen), results in the generation of the following code snippet for enums: export interface AnimalTypeMap { Dog: 0; Cat: 1; Fish: 2; Bird: 3; } export const AnimalType: Anim ...

Experience the power of combining React with typescript, webpack, and ui-router-react for

After carefully studying the ui-router-react documentation (), I am encountering several challenges with webpack compilation when importing import {UIRouter, UIView, UISref, UISrefActive, pushStateLocationPlugin} from 'ui-router-react'; This is ...

Switching TypeScript: transitioning typeof into an instance

Can someone help me understand how to tell TypeScript that a function returns instances of a specified class? class A extends HTMLElement { color: 'white' } function builder<T extends typeof HTMLElement>(classParam: T) { let instance ...

Designing the Firebase Structure of an Angular Application

What is the best way to structure Firestore and Angular for efficient querying? When using a JSON Cloud Firestore database, one of the challenges is inserting people and relating them to users. To optimize query speed and efficiency, it is important to c ...

The collapsible tree nodes overlap one another in the D3.js visualization

I'm currently working on integrating a d3 code into Power BI for creating a collapsible tree structure. Each node in the tree is represented by a rectangular box, but I've run into an issue where nodes overlap when their size is large. Below is t ...

What is the most effective method for creating a personalized select in Angular?

I am currently working with the MEAN stack (Angular 6) and exploring different methods to build a custom and reusable <select> form control that utilizes an array of strings fetched from the backend server to generate all the <option> tags. For ...

Creating a dynamic matrix table in Angular 2

I am looking to create a dynamic matrix table using Angular 2 that displays test results in a specific format: Test1 Test2 Test3 A 1,5 1,8 1,6 B 1,8 1,6 1,9 C 1,6 1,6 1,8 This example data demonstrates the structure ...

VSCode is unable to locate the typeRoots type declarations

I have organized all the type definitions that will be used in my application into a single file. I created a folder named @types and an index.d.ts file that exports every interface/type needed. I updated my tsconfig.json to include the @types folder: { ...

Using a custom TypeScript wrapper for Next.js GetServerSideProps

I developed a wrapper for the SSR function GetServerSideProps to minimize redundancy. However, I am facing challenges in correctly typing it with TypeScript. Here is the wrapper: type WithSessionType = <T extends {}>( callback: GetServerSideProps&l ...

What is the best way to programmatically download a file in Angular 4 without explicitly specifying the file name?

Below is the code snippet: importedSaveAs(blob, 'somefile.txt'); I'm currently facing an issue with hard-coding the file name in the above code. I would like to make it dynamic based on the response header. However, I'm unable to acc ...

Having trouble with Angular 5 tsconfig baseURL not functioning properly?

This may appear straightforward, but I am facing difficulties with it My Angular 5 application consists of three files located as follows: app_directory/tsconfig.json app_directory/src/app/services/my-service.service.ts app_directory/src/app/main/sub1/su ...