What is a quick way to assign object properties to another object in TypeScript?

Sample:

response.rooms.push({
  maxPlayers: doc.maxPlayers,
  ownderId: doc.ownderId,
  roomId: doc.ownderId,
  state: doc.state,
  type: doc.type,
});

All the parameters share the same name here. However, the doc object has additional parameters that I don't want to relate to rooms. Any suggestions? This is manageable with small objects but becomes tedious with larger ones.

Answer №1

The doc object contains certain parameters that should not be directly mapped to rooms.

It is important to explicitly specify which attributes you want to extract from the doc object. For larger objects, creating a function like buildRoom can help in shaping the output using dot access or destructuring, ultimately streamlining the process.

function buildRoom1(obj: typeof doc) {
  const {
    maxPlayers,
    ownerId,
    state,
    type,
    ...
  } = doc;

  return {
    maxPlayers,
    ownerId,
    roomId: doc.ownerId,
    state,
    type
  }; 
}
response.rooms.push(buildRoom(doc));

Alternatively:

function pluck<T extends Record<PropertyKey, any>, K extends keyof T>(obj: T, ...fields: K[]) {
    return fields.reduce((acc, field) => ({ ...acc, [field]: obj[field] }), {} as Pick<T, K>);
}
 
const room = pluck(doc, "ownderId", "state", "type", "maxPlayers");
response.rooms.push({ ...doc, roomId: room.ownderId });

Or with an additional level of abstraction:

function buildRoom2(obj: typeof doc) {
  const props = pluck(obj, "ownderId", "state", "type", "maxPlayers");
  return { ...props, roomId: props.ownderId };
}
response.rooms.push(buildRoom2(doc));

Answer №2

For those who are completely confident that the attributes consistently align, consider implementing the following solution:

data.rooms.push({...document})

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

Achieving a delayed refetch in React-Query following a POST请求

Two requests, POST and GET, need to work together. The POST request creates data, and once that data is created, the GET request fetches it to display somewhere. The component imports these hooks: const { mutate: postTrigger } = usePostTrigger(); cons ...

What is preventing Angular from letting me pass a parameter to a function in a provider's useFactory method?

app.module.ts bootstrap: [AppComponent], declarations: [AppComponent], imports: [ CoreModule, HelloFrameworkModule, ], providers: [{ provide: Logger, useFactory: loggerProviderFunc(1), }] ...

The variable X has been defined, but it's never actually utilized. Despite declaring it, I have not accessed its

I have encountered warnings in VSCode while using certain properties in my Angular component. The warnings state: '_id' is declared but its value is never read.ts(6133) (property) ItemEditComponent._id: number | undefined '_isModeEdit' ...

Leverage the JSON Web Token module within a Chrome extension

Currently in the process of developing a chrome extension but encountering an issue with loading the json web token node module in my Node.js setup. background-script.ts import jwt from 'jsonwebtoken'; // import * as jwt from '../node_mod ...

What is the best way to call an Angular component function from a global function, ensuring compatibility with IE11?

Currently, I am facing a challenge while integrating the Mastercard payment gateway api into an Angular-based application. The api requires a callback for success and error handling, which is passed through the data-error and data-success attributes of the ...

Transferring information from child to parent class in TypeScript

I have a scenario where I have two classes (Model). Can I access properties defined in the child class from the parent class? Parent Class: class Model{ constructor() { //I need the table name here. which is defined in child. } publ ...

Issue with Angular 7: "Unspecified name attribute causing control not found"

As I delve into the creation of my initial Angular application, I find myself faced with a series of errors appearing in the development mode console: ERROR Error: "Cannot find control with unspecified name attribute" ERROR Error: "Cannot f ...

receiving a null value in the JSON response

Preparing for the client to register. This function is responsible for registering a client. registerAsClient(){ this.loading =this.loadingCtrl.create({ content:"Setting up Account" }); this.loading.present(); this.buildClientData(); console.log( ...

A guide on leveraging Jest and Typescript to mock a static field within a class

While working with Typescript and a third-party library, I encountered an issue trying to write unit tests that mock out the library. Here's an example scenario: // Library.ts // Simulating a third party library export class Library { static code ...

Encountering a 403 error with RXJS when attempting to subscribe to a websocket in Angular

I am currently searching for a resolution to this issue without making any upgrades to Angular or its dependencies, as it could potentially impact other parts of the code base package.json { "name": "angular4", "version": "1.0.0", "description" ...

Issue with Nuxt2 CompositionAPI: Unable to showcase imported render function in component - Error message states "template or render function not defined"

I have created a render function that I believe is valid. I am importing it into a component and registering it within the defineComponent. However, when running the code, I encounter an error saying "template or render function not defined". I am confide ...

Converting an array into an object by using a shared property in each element of the array as the key

I have an item that looks like this: const obj = [ { link: "/home", title: "Home1" }, { link: "/about", title: "About2" }, { link: "/contact", title: "Contact1" } ] as const and I want to p ...

Testing Ag Grid's column headers using Jest and Angular CLI has proven challenging, as some columns from columnDefs remain elusive

Currently, I am using Jest and Angular Cli testing to validate column headers. In my attempt to replicate the process outlined on https://www.ag-grid.com/javascript-grid-testing-angular/#testing-grid-contents, I have encountered an issue where only 2 out ...

The elements within the NativeScript components are failing to show the data received from the Django API

My Django API is set up to provide a list of movies titles with their corresponding IDs. I've implemented a movie service in TypeScript that retrieves the list of movie titles and IDs using the GET operation. In my NativeScript project, I have two f ...

How should we correctly import jquery.inputmask?

Struggling to import jquery.inputmask using webpack and TypeScript? Head over to this discussion at Issue #1115 : Here's how I configured things with jqlite: To import in your app, use the following code: import InputMask from 'inputmask&apos ...

Creating dynamic dxi-column with different data types in dxDataGrid

Our team is currently working on an angular application that involves displaying records in a dxdatagrid. The challenge we are facing includes: Different schema each time, with data coming from various tables. The need to add/edit records. Displayi ...

How to fetch a file from a Spring Boot server using Angular 4

I'm currently developing a Spring Boot server with an Angular 4 front-end. I've created a service that allows users to download a .zip file from the front-end using HttpClient. Below is my code: Angular service: getZip(fileName: string) : Obser ...

How can you utilize a JavaScript library that provides global variables in Typescript?

I am closely adhering to the guidance provided in the official manual for declaration. Global library // example.js example = 20; Declaration file // example.d.ts declare const let example: number; Implementing the declaration file and library // ind ...

What is the best way to centralize JSDoc typedef information for easy sharing between different projects?

Currently, I am incorporating @typedef JSDoc comments at the beginning of my Javascript files to define types (primarily to access certain benefits of TypeScript without fully diving into it right now). I'm curious, where can I keep JSDoc typedef inf ...

Can you provide guidance on how to divide a series of dates and times into an array based

Given a startDate and an endDate, I am looking to split them into an array of time slots indicated by the duration provided. This is not a numerical pagination, but rather dividing a time range. In my TypeScript code: startDate: Date; endDate: Date; time ...