Transforming JSON keys in Angular

As a newcomer to angular and API integration, I am facing an issue with ngCharts in my project. The chart specifically requires the keys names in JSON to be "value" and "name", but the API I am using provides keys named "count" and "label". Is there a way for me to change the keys name in my code without modifying the API?

This is how I retrieve data from the API in my service:

  getSingleCustomerPurchasesChart(id:number) {
     return this.httpClient.get<typeof single>(`${environment.apiUrl}stat/prodaja/${id}`)
   }

Here is the model of data required for ngxChart:

 export var single: {
   value: number;
   name: string;
 }

And here is what the JSON from the API looks like:

[
    {
        "count": 123,
        "label": "Lorem ipsum",
        "id": "42807"
    },
]

Answer №1

To transform the data, try using the rxjs map operator:

fetchCustomerSalesData(id:number) {
  return this.httpClient.get<typeof fetch(`${environment.apiUrl}stat/sales/${id}`)
   .pipe(map(response => {
       return response.map((data) => {
        return {
         name: data.label,
         quantity: data.count,
        };
       }) 
   }))
}

Answer №2

If you're looking to tackle this problem using basic Javascript, I believe there's a solution available. However, it would be helpful for me to have some information about your specific data and the type of chart you intend to create in order to guarantee its functionality. Additionally, keep in mind that this code snippet is written in plain javascript:

const apiData = [
    {
        "count": 123,
        "label": "Lorem ipsum",
        "id": "42807"
    },
    {
        "count": 124,
        "label": "Lorem ipsum 2",
        "id": "42808"
    },
];

const chartData = apiData.map((e) => { 
    return { 
  name: e.label,
  value: e.count
  }
})

console.log(chartData);

For further information regarding the map method in Javascript, feel free to check out this link.

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

Steps to utilize redux in a fresh react class component

Within my App, there are two buttons - one for saving a message and another for creating a new component. import React from "react"; import { connect } from "react-redux"; import { AppState } from "./redux/store"; import { ChatState } from "./redux/chat/t ...

How to Retrieve the Name of the Active Element from an Unordered List (<ul>) in ReactJS and Display it in the

I have a project where I am creating a long navbar specifically for mobile devices, and I am structuring it in an accordion style. Initially, the view will show the currently active link name. When the user clicks on this active link name, it expands below ...

Unable to retrieve multiple values from a sinon stub

I am trying to stub a method using sinon in my Typescript code with Bluebird promises. However, I'm running into an issue where only the first value I set for the stub is being returned, even though I want it to return a different value on the second ...

Having trouble modifying the Input with split() in angularJS

I am faced with a nested JSON object that contains an array as one of its properties. Each item in the array is separated by a ';'. My goal is to use ';' as a delimiter to split each array item and make necessary changes. However, I am ...

Guidelines for segregating a Union from an Array

I'm currently utilizing graphql-code-generator to automatically generate TypeScript definitions from my GraphQL queries. I have a specific union within an array that I am trying to extract in TypeScript. Is this feasible? Although I came across an exa ...

Cleanse the email using express-validator, but only if it is recognized as an email format; otherwise, disregard

Currently, I am developing an API that requires users to input their username and password for authentication purposes (login functionality). Users have the option to enter their email, username, or mobile number. To ensure consistency, I need to normalize ...

Steps for submitting a form through an ajax callback

After delving into the world of Ajax, I encountered a problem that has me stumped. Initially, I am requesting data to populate a table, but I'm unsure how to tackle the issue. load_data(); function load_data(page) { $.ajax({ ...

Tips for using ArrayAdapter (Java) to input data into MySQL Server

As a newcomer to android development, I am looking to save call log details in a MySQL database. I have created a simple ArrayAdapter, but it is not displaying the data in the listview. Additionally, I need guidance on how to insert data into a MySQL serve ...

Tips for handling a function only after the model window has returned a promise in Angular 2

When a button is clicked, three functions are called in sequence within a promise. The first function is responsible for blocking a model window and returning a promise which then resolves the next function. The HTML code snippet is as follows: ...

Extract the string from a JSON document containing nested JSON objects and arrays, each with multiple JSON entities

Can someone guide me on how to properly format and display JSON data as shown below? Thank you! {"IsValid":true,"Values":{"editions":[]},"error":null} ...

Locate grandchildren elements using getElementById

My task is to modify the content and attributes of the table. The DOM structure is generated by a third-party tool, and I am using JavaScript to make changes in various sections. <div id="myId"> <div> <div> <table&g ...

Moving from one page to another

I am attempting to create a transition effect between sections within a single-page application. All the sections are contained on the same page, with only one section displayed at a time while the rest are set to display none. When a specific event is tri ...

Is it possible to enable communication between all instances within the same Security Group in Cloud Formation JSON?

I am currently working on constructing a Cloud Formation JSON file to outline EC2 Instances and Security Groups. One of the tasks I have is creating a security group that allows all instances within it to freely share data among themselves. This was the ...

Lazy Load immediately loads images that are visible on the screen without needing a click

I am facing an issue with Lazy Load on my image-heavy website. I want the images to load only when a button is clicked, but currently, it only partially works. Images below the fold follow the desired behavior of loading on click, but those above the fold ...

Tips for Using Sed to Remove the Final Character of the Previous Line

My goal is to remove a line with the last character of the previous line using sed: This is an example of a json file : { "name":"John", "age":"16", "country":"Spain" } I want to delete the "country" field from all entries in the file. To do this, I nee ...

Express displays html instead of json when error handling occurs

I recently followed a tutorial on Express.js to create a simple error handler. function clientErrorHandler(err, req, res, next) { if (req.xhr) { console.log('clienterrorhandler', err); res.status(500).send({ error: 'Something faile ...

SystemJS is loading classes that are extending others

In my Angular2 application, I have two classes where one extends the other. The first class is defined in the file course.ts (loaded as js) export class Course { id:string; } The second class is in schoolCourse.ts (also loaded as js) import {Cours ...

The dropdown menu button stubbornly remains open and refuses to close

Having an issue with a dropdown menu button where it should open when clicked on the icon and close when clicking off the icon or on the icon again, but instead, it remains open. Here is a screenshot for reference: https://i.stack.imgur.com/UX328.jpg I&a ...

Setting up initial values for React properties

Below is the React code snippet I am currently working with: this.state = { colsHiddenStatus: new Map([['rowNumber',true], ['id', false], ['firstName', false], ['lastName', false], ['mobile', false], [&a ...

Measuring the frequency of API calls through HttptestController

I need to track the number of times an API is being called, and I am using HttpTestingController to achieve this. When const req = httpMock.expectOne('/api/getrecords'); fails it('should return one object', () => { var dummyO ...