Is there a way to establish a pre-defined key in a mat-table?

I am fetching data from an API and I need to display it in a key-value format on a mat table. The keys are predefined and not provided by the API.

The data retrieved from the API is shown here: image1

I want to display it on a mat table like this: mat table image

Therefore, I am attempting to structure my main data in a key and value format as follows:

dataAddress = [
        {key: "Company Name", value: "Abuja Corp"},
        {key: "Company Address", value: "1-301, Sector 18,"},
        {key: "Email Address", value: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f39a9d959cb3949e929a9fdd909c9e">[email protected]</a>"},
        {key: "Phone number", value: "9999999999"},
    ];

I have attempted the following:

interface Data{
    key:string;
    value:string;
}

const keys =[
    'Company Name',
    'Company Address',
    'Email Address',
    'Phone Number'
]

})
export class CompanyInformationComponent implements OnInit {
    currencies = [];
    dialogRef: any;
    header = [{name: "Company Information"}];
    //dataAddress:any;
    dataAddress = [
        
    ];
    dataSetting = [
        {id: 1, key: "Home/local currency", value: "Naira"},
        {id: 2, key: "International Currency", value: "USD"},
        {id: 3, key: "Auto-Post JV?", value: ""}
    ];
    displayedColumns: string[] = ['key', 'value'];

    constructor(
        private companyInformationService: CompanyInformationService) {
    }

    ngOnInit(): void {
        this.refresh();        
    }
 
    refresh() {
        this.getCompanyInformation();
    }

    getCompanyInformation()
    {
        
        const data1 ={};
        this.companyInformationService.getCompaniesInformationList().subscribe(data => {
            this.dataAddress = data.items;
            console.log("data",this.dataAddress);

           const newData: Data[] =[];

           for(const prop in this.dataAddress){
               newData.push({
                key:keys,
                value: this.dataAddress[prop]
               });
           }
        });
    }  

}

However, I encountered this error :

 Type 'string[]' is not assignable to type 'string'.ts(2322)
Untitled-1(2, 5): The expected type comes from property 'key' which is declared here on type 'Data'

Answer №1

let mapping =[
    {oldKey:'name', newKey:'Company Name'},
    {oldKey:'address', newKey:'Company Address'},
    {oldKey:'email', newKey:'Email Address'},
    {oldKey:'phone', newKey:'Phone Number'},
];

const dataArray: Data[] = [];
for (const item of this.addressDataArray) {
    for (const map of mapping) {
        dataArray.push({ keyTitle: map.newKey, valueInfo: item[map.oldKey] });
    }
}

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

Combining different sub types using the | symbol - Exploring the power of Union Types

I have a custom type called Entry which includes: export type Entry = { number: number position: number entryItem: Banana | Orange } Additionally, I have defined the following types for entryItem: Banana Type export type Banana = { number: number ...

Updating the styles of React Native components using stylesheets

I've created a unique React component with the following structure: import { StyleSheet } from 'react-native'; import { Input, Item } from 'native-base'; import Icon from 'react-native-vector-icons/FontAwesome'; import { ...

Vue component prop values are not properly recognized by Typescript

Below is a Vue component I have created for a generic sidebar that can be used multiple times with different data: <template> <div> <h5>{{ title }}</h5> <div v-for="prop of data" :key="prop.id"> ...

Do I need to convert AngularJS to .ts for an Angular/AngularJS hybrid application?

Currently in the process of upgrading from AngularJS v1.25 to Angular 14 using the ng-Upgrade approach outlined on angular.io/guide/upgrade. Adding an extra challenge, our main page is built with ASP.NET MVC 5, and I am aiming to incorporate the Angular CL ...

Modifying variable assignments in an Angular index.html file according to the environment

Is it possible to dynamically set the config.apiKey value in Angular based on different environments such as Development and Production? In a Production environment, use config.appKey = 'AB-AAB-AAB-MPR'; In a Development environment, use config ...

Having difficulty resolving the fs and child_process modules

Even though I've come across numerous questions with similar situations, none of them have provided the solution I need. I'm attempting to utilize the 'ffmpeg-static-electron' dependency on Angular Electron. After running npm install ...

Find the element that is being scrolled in order to delete its attributes

Issue with the sidebar causing whitespace on mobile devices, and scroll properties need to be removed. When expanding the sidebar, white space appears below it. Various display modes have been tried, but they all push elements below instead of keeping th ...

Ways to implement a package designed for non-framework usage in Vue

Alert This may not be the appropriate place to pose such inquiries, but I am in need of some guidance. It's more about seeking direction rather than a definitive answer as this question seems quite open-ended. Overview I've created a package th ...

Determine the specific data types of the component properties in React Storybook using TypeScript

Currently, I am putting together a component in the storybook and this is how it appears: import React, { useCallback } from 'react'; import { ButtonProps } from './types'; const Button = (props: ButtonProps) => { // Extract the nec ...

Extract data from Angular2 class

I am having trouble with the data binding of {{value}}. Here is a straightforward example: app.component.ts import {Component, OnInit} from "@angular/core"; @Component({ selector: "app", templateUrl: "./app/app.html" }) ...

Deleting elements from an array of objects in Angular Would you like help with

I have a JSON structure and I need to remove the entire StartGeotag object from the array. [{ CreatedDate: "2022-02-17T10:30:07.0442288Z" DeletedDate: null ProjectId: "05b76d03-8c4b-47f4-7c20-08d9e2990812" StartGeotag: { ...

How to effectively handle null values using try..catch statement in typescript

As a beginner, I am learning how to write a try/catch statement in TypeScript. My issue is that there is a function within the "try" block that returns null. How can I implement code in the "catch" block specifically for when the function in "try" returns ...

Is it possible to transfer parameters from one page to another page using the pop method in Ionic 2?

Is it possible to pass parameters from one page to another during a push operation, but how can this be done during a pop operation? showfilter(){ this.navCtrl.push(FilterPage,{ fulldetail : this.selectedarea }); } Can you explain how ...

Installing Angular 4 in Visual Studio 2017

Looking to build an Angular web application using Visual Studio 2017. Starting with a new project by selecting Asp.net Web application with Empty template. Feeling unsure about which files need to be copied/included in the project based on the attached sc ...

Angular 2: A helpful guide on how to duplicate an object within another object

I'm seeking assistance on how to duplicate an object into another object using Angular 2. Previously in Angular, I utilized angular.copy() to duplicate objects to the vague reference of the original ones. However, when attempting the same in Angular ...

Having difficulty passing a function as a parameter from a NextJS component

I have a code snippet like this in a NextJS component: const [currentGPS, setCurrentGPS] = useState({coords:{latitude:0.0,longitude:0.0}}) useEffect(() => { utl.getGPSLocation( (v:{coords: {latitude:number; longitude:n ...

Leveraging RXJS Observables and Subjects in combination with Redux is an effective strategy for efficiently managing and processing data

My current project involves utilizing a redux architecture alongside Observables. It has come to my attention that I need to handle data processing after retrieving data from various asynchronous sources. The process is intended to function as follows: ...

Please exclude any files with the name npm-debug.log.XXXXXX in the .gitignore file

Is there a way to exclude this file from the repository using .gitignore? https://i.stack.imgur.com/mK84P.png I am currently working on Gitlab. I have attempted the following: https://i.stack.imgur.com/2kN21.png Appreciate any help in advance ...

Retrieve a collection of nested dictionaries containing flask and angular data

In my app development journey with flask and ionic(angular), I'm working on returning a JSON list. Here's the python code snippet: def get-stocks(): # Select all stocks cursor.execute("""SELECT * FROM `tbl_symbol_index`"" ...

What is the best way to trigger a 'Save As' dialog box on a browser when a button is activated within an Angular application, guaranteeing cross-browser compatibility?

The solution needs to be compatible with both Windows and Mac operating systems. Additionally, we should be able to specify a default file name and type. ...