Can we incorporate the typescript map into the object's properties?

I have defined the structure of MenuItem as follows in order to parse the response from the server side rest api:

  type MenuItem = {
    id: number;
    name: string;
    path: string;
    tree_id_path: string;
    children: MenuItem[];
  };

The server side is returning more than 4 fields, but I only want the MenuItem to contain those 4 fields. How can I achieve this? Currently, I am using the 'as' keyword to cast the response to a list of MenuItem.

  export async function roleMenuTree(options?: { [key: string]: any }) {
    let response = await request<API.ApiResponse>('/manage/permission/role/v1/role/menu', {
      method: 'POST',
      body: JSON.stringify({}),
      ...(options || {}),
    });
    let dataList = response.result as API.MenuItem[];
    return dataList;
  }

Answer №1

One effective way to accomplish this task is by utilizing ES6 features.

Utilizing the Spread syntax can help simplify the process.

let { unwantedData ,...remainingData} = response.results;
let updatedResult = remainingData;

Alternatively, you can also employ the Destructuring assignment method to specifically select the properties you want.

let {id, name, path} = response.results;
let updatedResult = {id, name, path};

Answer №2

To explore another option, consider creating a fresh object

export async function createRoleMenuTree(options?: { [key: string]: any }) {
    let response = await request<API.ApiResponse>('/manage/permission/role/v1/role/menu', {
      method: 'POST',
      body: JSON.stringify({}),
      ...(options || {}),
    });
    let newTree: MenuItem = {
      id: response?.result?.id,
      name: response?.result?.name,
      path: response?.result?.path,
      tree_id_path: response?.result?.tree_id_path,
      children: //Define your MenuItem[]
    }
    let dataList = newTree;
    return dataList;
  }

Alternatively, you can opt for this method (if the API response fields have the same names)

   let {id, name, path, tree_id_path, children} = response.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

Ways to EXPAND styled components from imported components

After researching the styled components documentation, I discovered that in version 4+, the "as" prop should allow me to extend my imported component. However, I am having trouble getting it to work. COMPONENT: type Options = { margin: strin ...

Removing the AM and PM from OwlDateTime in Angular is simple since the time format is already in 24-hour time

Using OwlDateTime in a 24-hour format: <div *ngIf="isSchedule" class="form-inline"> <label style='margin-right:5px ;margin-left:210px'> Date Time: <input [owlDateTimeTrigger]="dt" [owlDateTime]="dt" class="form-control" placeh ...

To set up the store in configureStore, you must provide one type argument for the 'MakeStore' generic type

Encountering an issue with MakeStore showing a Generic type error 'MakeStore' requires 1 type argument(s) .ts(2314) Here is the code from configureStore.ts: import { configureStore, EnhancedStore, getDefaultMiddleware, } from '@reduxj ...

Unable to display toast notification in React/MUI/Typescript project

Currently tackling error notifications targeted at 400,401, and 500 errors within a large-scale project. I am facing an issue where I want to integrate my ErrorToastNotification component into my layout.tsx file to avoid duplicating it across multiple page ...

Interference of NestJS provider classes in separate event loops causing conflicts

I'm currently facing an issue where my shared library injectables are conflicting with each other. The bootstrap file initiates this file alongside a proxy server to start local microservices import { serviceA } from '@company/serviceA' imp ...

Incorporating a module with the '@' symbol in a Node, Express, and Typescript environment

I recently started using Node and Typescript together. I came across a file where another module is imported like this import { IS_PRODUCTION } from '@/config/config';. I'm confused about how the import works with the @ symbol. I could real ...

Angular - Automatically update array list once a new object is added

Currently, I'm exploring ways to automatically update the ngFor list when a new object is added to the array. Here's what I have so far: component.html export class HomePage implements OnInit { collections: Collection[]; public show = t ...

Upon initialization, navigate to the specified location in the route by scrolling

My page has various components stacked one after the other, such as: <about></about> <contact></contact> I am utilizing the ng2-page-scroll to smoothly scroll to a particular section when a navigation link is clicked. However, I a ...

Encountered an issue with the Dynamic Form: TypeError - The property 'value' is undefined and cannot be read

RESOLVED An incorrect value was causing an issue with the onChange function. public onChange = (e:any, key:any) => { this.setState({ [key]: e.target.value }); }; I'm struggling to resolve an error while inputting data into my form in T ...

The type "AppRouterInstance" cannot be assigned to type "nextRouter"

Within my Next.js project, a registration form is included as seen below: "use client"; import * as React from "react"; import { zodResolver } from "@hookform/resolvers/zod"; import { useForm } from "react-hook-form" ...

Eliminating the need for RequireJS in the Typescript Visual Studio project template

After integrating RequireJS into my Typescript template using the nuget package manager, I found that it was more than what I needed and decided to uninstall it. Even though I removed the package through nuget and the files were deleted properly, my Typesc ...

Solving the "ExpressionChangedAfterItHasBeenCheckedError" in Ionic: A Guide

//html <span style="margin-left:43%;background-color:rgb(229,229,229);border- radius:10%">&nbsp;&nbsp;{{formatEpoch(epoch)}}&nbsp;&nbsp;</span> //ts lastdate:any; formatEpoch(epoch): string { ...

invoke a specified function at runtime

I recently came across a useful library called https://github.com/ivanhofer/typesafe-i18n This library has the capability to generate strongly typed translation data and functions, as illustrated below. (the examples provided are simplified for clarity) e ...

Is it possible to modify the default behavior of a sensitive region within a button?

I created a calculator application in React and overall, it's working fine, however... I've noticed that when I hold a click longer, it only registers as a click if the mouse was pressed down and released on the button itself. Although I unders ...

Is it possible to retrieve cached data from React Query / Tan Stack Query outside of the React tree?

Currently, I am in the process of developing an error handler for our mobile app that will send user data to the server when unexpected errors occur. Previously, I was able to easily retrieve user information from a global state. However, after removing t ...

Hand over the component method as an argument to a class

One of my components, called First, is responsible for creating a new instance of a Worker class. During the creation process of this class, I intend to pass the Read method as a callback method. Once this class completes its task, it will then invoke thi ...

Capture data from a Telegram bot and store it in a Google Sheet

I am trying to use a spreadsheet through a Telegram bot as a TODO list so that when I input something on my phone, it is saved in the spreadsheet. (I'm following this tutorial https://www.youtube.com/watch?v=XoTpdxbkGGk, which seems accurate with Goog ...

Angularfire2 retrieve list of data with a specified number of items from the

I am facing a challenge in retrieving a specific node from my firebase database. https://i.sstatic.net/YDevB.png The technologies I am using include: "angularfire2": "^5.0.0-rc.4", "firebase": "^4.9.0", In my component code, you can find the following ...

Passing the value of an Angular component to a different component

I have a menu in my application that uses IDs to route content, and I also have a detailed view where the content should be displayed based on those same IDs. Currently, I am trying to display objects by their ID when a button is clicked. However, I' ...

Stream in Node.js seems to have frozen

I am looking to develop a basic csv parser using the csv module and effectively handle errors when the file is missing. If I remove the sleep functions, the code successfully reaches the Finally statement (and produces an error output). What am I overloo ...