Is it possible to rename an object that is received from the server using Typescript and Angular?

When receiving data from a service, it comes in the following format

YourData.ts file

export interface YourData {
    first_name: number;
    last_name: number;

In Angular UI, I want to display the format in lower camel case

html file

firstName is {{firstName}}
lastName is {{lastName}}

Where should I make this change and how can it be done?

I have an idea but not sure if it's correct

export const parseFromServer = (response:any) =>{
    return {
        firstName : response.first_name
    }
}

Answer №1

UPDATED INFORMATION:

To maintain the use of the same object but with updated key names, follow the approach of adding a new key and deleting the old key. For reference, please review the previous response if you intend to work with a new object.

    var oldObject: any = {
        first_name: 1,
        last_name: 2
    }
    var keys = Object.keys(oldObject);
    for(var key in oldObject) 
    {
        let words = key.split("_");
        oldObject[words[0][0].toLowerCase() + words[0].substring(1) + words[1][0].toUpperCase() + words[1].substring(1)] = oldObject[key]; // add new key
        delete oldObject[key]; // delete old key
    }
    console.log(oldObject)

Ensure that the key names are unique and follow the word format {word1}_{word2}.

PREVIOUS RESPONSE:

Based on your query, it appears you want to change the keys of your object from something like first_name to firstName. While direct renaming is not possible, creating a new object with desired key names is an option.

If you already know the key names, you can easily create a new object:

var oldObject = {
    first_name: 1,
    last_name: 2
}
var newObject = {
  firstName: oldObject.first_name,
  lastName: oldObject.last_name
}; 
console.log(newObject)

If the key names follow the format {word1}_{word2}, without prior knowledge, custom logic is required. Here's a sample approach:

var oldObject: any = {
    first_name: 1,
    last_name: 2
}
var newObject: any = {};
var keys = Object.keys(oldObject);
for(var key in oldObject) 
{
  let words = key.split("_");
  newObject[words[0][0].toLowerCase() + words[0].substring(1) + words[1][0].toUpperCase() + words[1].substring(1)] = oldObject[key];
}
console.log(newObject)

Access the playground for further exploration.

Answer №2

Here is a helpful resource that may work for your situation -

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 issue of null ngModel binding during the OnInit phase in Angular 2

Encountered an issue with Angular 2 ngModel binding, leading to unexpected behavior. Check out the plnkr When using ngModel to bind a value to a child component, I noticed that the value is not populated in the OnInit function of the child component. For ...

Warning: Google Map API alert for outdated Marker Class

Working on an application using the Google Maps TypeScript API, I came across a warning message when launching the app -> As of February 21, 2024, google.maps.Marker will no longer be available. Instead, developers are advised to use google.maps.marke ...

Seeking a guide on how to effectively utilize Angular 6 for consuming REST API and performing CRUD operations

I am a beginner with Angular and I am currently using Version 6, specifically the CLI tool. My main focus right now is learning how to make REST API calls. I have searched for tutorials on this topic but unfortunately, none of them have been successful fo ...

The setInterval function is active in various components within Angular 6

Recently, I started using Angular(6) and incorporated the setInterval function within a component. It's functioning properly; however, even after navigating to another route, the setInterval continues to run. Can someone help me determine why this is ...

The functionality of external linking seems to be malfunctioning within Angular 2

Take for instance the website: The routing system is in place so that when you click on pages or links, the URL changes to something like: /articles /work /articles/1 However, if you were to click on this link: A 404 error is thrown. How can I configur ...

Angular: Differences Between "Partial" and "Full" Compilation Modes

Is there a reason why the library compiled in "partial" mode takes longer to build within the consumer application compared to the "full" compilation mode? ...

What is the process of adding new fields to a model in TypeScript?

I have created a test.model.ts file: export interface ITransaction { description: string; transactionDate: string; isDebit: boolean; amount: number; debitAmount: string; creditAmount: string; } export class Transaction implements ...

The Expo React Native project encountered an Android build failure

I have a project that was created using expo 49 and typescript 5.1.3, and now I need to prepare it for submission to Google Play. To achieve this, I followed a series of steps in the VS Code terminal: 1) Ran npm install -g eas-cli 2) Executed eas login ...

Is it possible to utilize Angular CLI for publishing Angular2 components on NPM?

Is it possible to leverage the Angular CLI to develop and distribute an Angular 2 component on NPM and Github? Are there specific coding procedures that need to be adhered to in order to meet the criteria for publishing the component? ...

Guide on customizing VS Code's Explorer to display angular js icons

How can you customize the icons displayed in Explorer within VS Code by adding a specific addon procedure? https://i.sstatic.net/KSMwC.png https://i.sstatic.net/2mFMq.png ...

Limit the outcomes of the Ionic timepicker

Currently, I am utilizing the ionic datetime feature. However, instead of receiving just the hours, minutes, and seconds, the result I am getting looks like this 2020-10-05T00:00:27.634+07:00. What I actually require from this output is only 00:00:27. Is ...

There was a Runtime Error that occurred, stating a TypeError: It is not possible to access properties of an undefined value (specifically

I've encountered an issue with a donut chart implemented from react-apex charts. Every time I try to render the page containing the chart, an error occurs. However, if I make changes to a property of the chart, it renders without any errors on the fro ...

Encountering difficulty utilizing Partial with a generic type

I'm currently working on developing a class called Map that will store mappings set by other classes, such as CharacterManager. I want the content of the map to be determined by other classes, so I have designed the Map class to accept a generic typ ...

ParcelJS takes a unique approach by not bundling imported JavaScript libraries

My NodeJS app, which is a Cloudflare Worker, seems to be having trouble with bundling the 'ping-monitor' dependency. In my main typescript file (index.ts), I import the handler module and the first line reads: const Monitor = import('ping-m ...

How can I trigger a function in Angular 7 when Bootstrap Collapse expands?

In my Angular 7 project, I am creating a Hacker news clone where I want to implement a feature that allows users to see child comments when they click on a button next to a comment. To achieve this, I have integrated Bootstrap 4 Collapse into my project. ...

Exploring the Depths of Nested Arrays: A Guide to Efficiently

My array has a nested structure like this: "meetingTime":[ [ { "date":"2021-05-30", "startTime":"15:30", "endTime":"11:11&quo ...

Using functions like .map in a TypeScript model may not function properly

After retrieving data from a server, I created a TypeScript model to structure the incoming data as follows: export class DataModel{ public PageNo: number public showFromDate: string public showToDate: string public gradeFieldId: number } ...

Error message: "No such file or directory found for Angular ng"

Recently, I encountered an issue while attempting to host an Angular app on a server. When using the command ng serve, it returned an error stating "No such file or directory," despite the fact that the ng command is visible in the image below. https://i. ...

Enhance your MaterialUI Button with a higher order component that accepts a component

I am currently working on implementing a Higher Order Component (HOC) for the MaterialUI Button component: import {Button as MUIButton, ButtonProps} from '@material-ui/core'; import * as React from 'react'; export const Button = (props ...

Utilizing dynamic data within the ng-template

As a newcomer to Angular, I am facing a challenge in passing a string into a template. My goal is to create a reusable template or component that can display instructions on how to proceed with an action. Currently, I am achieving this by using the follow ...