Creating personalized mapping for TypeScript objects

I have a TypeScript object structure that resembles the following:

{
    "obj1" : { object: type1;};
    "obj2" : { object: type2;};
    "obj3" : { object: type3;};
    "obj4" : { object: type4;};
    "obj5" : { object: type5;};
}

My goal is to transform it into:

{
    "obj1" : type1;
    "obj2" : type2;
    "obj3" : type3;
    "obj4" : type4;
    "obj5" : type5;
}

I am specifically concerned about maintaining the types while performing this transformation.

I am currently utilizing TypeScript version 3.7.2, however, I am open to solutions from later versions as well.

Can anyone provide assistance with this?

UPDATE ---- It's important to clarify that my issue revolves around preserving the typings rather than simply mapping objects. I want the types of my objects to be accurately represented during compile time.

Answer №1

Is this what you were looking for?

interface Foo {
  obj1: { object: string };
  obj2: { object: number };
  obj3: { object: boolean };
}

type FooMapped = { [key in keyof Foo]: Foo[key]["object"] };

const foom: FooMapped = {
  obj1: "obj1",
  obj2: 432,
  obj3: true
}

Here is a more versatile solution:

function mapObject<R extends Record<string, { object: unknown }>>(record: R) {
  let ret: any = {};
  Object.keys(record).forEach((key) => {
    ret[key] = record[key]["object"];
  });

  return ret as {
    [key in keyof R]: R[key]["object"];
  };
}

const foo = mapObject({
  bar: { object: 412 },
  baz: { object: true }
});

console.log(foo);

Answer №2

Check out this snippet of code:

let items = {
    "item1" : { "thing": "stuff1"},
    "item2" : { "thing": "stuff2"},
    "item3" : { "thing": "stuff3"},
    "item4" : { "thing": "stuff4"},
    "item5" : { "thing": "stuff5"},
};
for (let element of Object.keys(items)) {
  items[element] = items[element]['thing'];
}
console.log(items);

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

The npm script for running Protractor is encountering an error

Currently, I am facing an issue while trying to execute the conf.js file using an npm script. The conf.js file is generated within the JSFilesRepo/config folder after running the tsc command as I am utilizing TypeScript in conjunction with protractor-jasmi ...

unable to assign an array to a different array in typescript

I'm facing an issue with assigning values to the private kitems array in my class. Despite defining it as kitems:any[], when I try to assign a value using this.kitems = items; and then log this.kitems, it shows up as an empty array. createprofile() { ...

Exploring the functionality of the Angular snackbar feature

I have created a simple snackbar with the following code: app.component.ts: ngOnInit(){ this.dataService.valueChanges.pipe( filter((data) => data === true), switchMap(() => { const snackBarRef = this.matSnackBar.open ...

Utilizing a setup module for configuration purposes

In the process of developing my angular application, I have integrated several external modules to enhance its functionality. One crucial aspect of my final application is the configuration classes that store important values like URLs and message keys us ...

Changing an element within an item stored in Ionic Storage

Hello, I am currently attempting to update a specific part of an object stored in Ionic storage. The current data in the Storage looks like this: key : object value : {a: "1", b: "2", c: "3"} To modify one of the values to 10, I created the following fu ...

Ways to retrieve form information from a POST request

I received a POST request from my payment gateway with the following form data: Upon trying to fetch the data using the code snippet below, I encountered errors and gibberish content: this.http .post<any>('https://xyz.app/test', { ti ...

Retrieve the product IDs by selecting the checkboxes, then compile a fresh array consisting of the identified IDs

I am currently delving into the realm of typescript/angular2+ as a fledgling student, and I have taken on the task of creating a website to put my newfound knowledge to the test. The view is up and running, but I'm facing some roadblocks as I work on ...

Error: Missing provider for MatBottomSheetRef

While experimenting in this StackBlitz, I encountered the following error message (even though the MatBottomSheetModule is imported): ERROR Error: StaticInjectorError(AppModule)[CountryCodeSelectComponent -> MatBottomSheetRef]: S ...

Ways to retrieve the most recent update of a specialized typing software

When attempting to run typings install in a sample project with the below typings.js file, I received a warning. How can we determine the latest version number and what does the number after the + symbol signify? { "globalDependencies": { "core-js ...

How to iterate through properties declared in an Interface in Angular 12?

Before Angular 12, this functioned properly: export interface Content { categories: string[] concepts: Topic[] formulas: Topic[] guides: Topic[] } //this.content is of type Content ['formulas', 'concepts'].forEach(c =&g ...

Troubleshooting the issue of Angular 2 error: Cannot access the 'getOptional' property

Currently, I am navigating my way through angular 2 and attempting to define a service named searchservice. I want to inject this service in the bootstap part of my project: import {SearchService} from 'src/service'; Here is the code for the Se ...

What is the reason behind decorators needing to utilize apply(this) on a function?

I've been delving into the realm of JavaScript and exploring decorator code. One thing I've noticed is that when looking at decorator code like the example below, the input function always applies to 'this' even though it doesn't a ...

Search functionality in Angular using column-based filtering algorithm

Take a look at my table view below. Each column has its own search function. My current issue is that when I type in one column, the same text appears in other columns as well. To solve this problem, I have implemented the following code: <tr& ...

What is the best way to fetch the chosen item in an Angular select dropdown

I am working on a dropdown that populates with items of type ObjectA. item.component.html: <label>items list: <select formControlName="itemsCtl" (change)="onChange()"> <option *ngFor="let item of itemList" [value]="item">{{i ...

Typed NextJs navigation to a specific route

<Link href="/about"> <a>About Us</a> </Link> Is there a way to ensure type safety with NextJs links? Currently, it is challenging to restructure the Link component as it is just a string. I stumbled upon this repos ...

Having constant problems with ngModel twoway binding. Any suggestions on how to successfully bind to a property in order to update an api link?

I am attempting to implement two-way binding in order to dynamically change the API endpoint when a button is clicked. The value attribute of the button should be used as part of the API URL string. I tried following an example in the Hero Angular App, bu ...

Error with Chakra UI and React Hook Form mismatched data types

Struggling with creating a form using ChakraUI and React-Hook-Form in TypeScript. The errors seem to be related to TypeScript issues. I simply copied and pasted this code from the template provided on Chakra's website. Here is the snippet: import { ...

Using React-Router-Native to send an image as a parameter

I am encountering an issue while attempting to pass an image as a parameter in react-router-native and retrieve the data from location.state. Typically, I use the following code to display an image: import Icon from '../image/icon.png'; <Vie ...

Tips for bringing in Cassandra driver types in TypeScript?

In the documentation for the Cassandra driver, they provide code examples like this: const Uuid = require('cassandra-driver').types.Uuid; const id = Uuid.random(); However, when attempting to use this in Visual Studio Code, the Uuid class type ...

The compiler is unable to locate the node_module (Error: "Module name not found")

Error: src/app/app.component.ts:4:12 - error TS2591: Cannot find name 'module'. Do you need to install type definitions for node? Try npm i @types/node and then add node to the types field in your tsconfig. 4 moduleId: module.id, When att ...