Extracting information from an object retrieved through an http.get response can be accomplished by utilizing various methods and

I am working with an API that returns a JSON object like this:

 {
    "triggerCount": {
        "ignition_state_off": 16,
        "ignition_state_on": 14,
        "exit_an_area": 12,
        "enter_an_area": 19,
        "door_unlocked": 1,
        "door_locked": 1,
        "fuel_level_below": 12
    }
}

The response is obtained using the following service :

interface ITrigger{
  triggerCount: ITriggerCount;
}

interface ITriggerCount{
  [key:string]: number;
}


@Injectable()
export class DbApiService {

   private triggersUrl = 'http://localhost:3000/triggers';

  constructor(private http: HttpClient) {
  } 


getTriggerCount(){
  return this.http.get<ITrigger>(this.triggersUrl)
  }

}

Component where the service is injected:

export class TriggersComponent implements OnInit {


@Input() triggerCountChart = [];

triggers:any;
tempArray: any = [];

  constructor(private triggerService: DbApiService) { }

  ngOnInit() {

    this.getTriggerCount()
    this.buildChart()

  }


  getTriggerCount(){


  this.triggerService.getTriggerCount().subscribe(data =>{this.triggers = data;
    this.tempArray = this.triggers.triggerCount;
    console.log(this.triggers,this.tempArray);
        } );

}

I log the response results to check the data, screenshot here :

https://i.sstatic.net/RHbSO.png

In order to render a chart, I need to extract attribute strings like ignition_state_off and save them in a string array along with their corresponding values in a number array.

Chart Function

The chart currently uses manually inserted data. Here's the function:

buildChart(){

  let triggerLabels = ['ignition_off','ignition_on','enter-area','exit-area','door_unlocked','door_locked','fuel_drop'];

  let triggerCountArray = [12,13,22,32,14,8,17]

  this.triggerCountChart = new Chart('canvas-triggers', {
    type: 'pie',
    data: {
      labels: triggerLabels,
      datasets: [
        { 
          data: triggerCountArray,
         // borderColor: "#3cba9f",
          backgroundColor: ["#e8f1f2","#b9c0c1","#8d99ae","#3283a9","#006494","#283c4e"],
          fill: false
        },

      ]
    },
    options: {

      title: {
        display: true,
        text: 'applets created in percentage',
        fontSize:14
    },
      legend: {
        display: true,
        position: "right",
        labels: {
          boxWidth : 40,
          fontSize : 14
        }
      },
      scales: {
        xAxes: [{
          display: false
        }],
        yAxes: [{
          display: false
        }],
      }
    }
  });


}

I need help to properly extract and use the API response for the chart. Thank you!

Answer №1

After reviewing the feedback provided in the comments, it is clear that extracting information to align with your desired data structure is crucial.

One approach to achieve this is by initially extracting the keys and then restructuring your data as shown below:

Object.keys(this.tempArray).reduce(function(current, item) {
  current.labels.push(item);
  current.values.Push(this.tempArray[item]);
  return current;
}, { labels: [], values: [] });

In this solution, Object.keys(this.tempArray) is used to extract all keys from the object into a string array. Subsequently, Array.prototype.reduce facilitates looping over the data while retaining the relevant information. The optional second parameter sets the initial function, where each subsequent iteration builds upon the previously returned value.

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

Having trouble reading JSON file using Pandas

data=pd.read_json("https://api.covid19india.org/state_district_wise.json") data transposed_data = data.transpose() transposed_data I'm working on extracting districtData from this API but I'm facing difficulties. The column contains key-value p ...

Using Angular to handle routes with a specific domain prefix

Let's say I own the domain https://example.com and I'd like to create a subdomain specifically for my blog, like this: https://blog.example.com. How would you handle the routing for this scenario using Angular? ...

Secure your TypeScript code by encapsulating it with protection mechanisms and distribute

Currently in the process of constructing an internal TypeScript "library" using webpack 1.14. I've set up an npm package and have it published on a private feed, which is working smoothly (able to utilize classes and interfaces from the library in o ...

Guide on achieving horizontal scrolling in Ionic 3

Check out this image I have a list of 10 names in an ion-scroll, but they are appearing on separate lines like paragraphs. Below is my HTML code: <ion-scroll scrollX="true" style="width:100vw; height:50px" > <ion-row class="headerChip"& ...

Utilize VueJS to retrieve JSON data

onMounted(() => { productService.value .getProducts() .then((data) => (products.value = data)); console.log((products)) }); Upon inspecting the products object using console.log, I noticed the following. screenshot of the console outpu ...

Sending JSON data with an ASP.NET Post request

My task involves connecting to a server via Json request. The server admin specified that an https server needs to be installed. I purchased and installed an SSL on my server as per the requirements. However, each time I attempt to make a request, I encou ...

Tips for converting "{Key=Value}" structures to JSON using Python

When I execute an Athena query in AWS, the results contain structs with key/value pairs formatted like this: { "events": "[{deviceType=Android,logins=400},{deviceType=iPhone,logins=550}]" } While I can use regular expressions to pa ...

The module 'AnotherModule' in a different file has unexpectedly imported a value 'Module in file'. Make sure to include a @NgModule annotation to resolve this issue

After struggling with this problem for the past four days, I've exhausted all resources on Stack Overflow and Google. Hopefully, someone here can provide some insight. I have two Angular 11 libraries - one core and the other called components. Compone ...

Interactive form control for location details including country, state, district, and town

I am struggling with adding dynamic form controls on dropdown change. I have been able to add them, but encountered an error preventing me from retrieving the value in 'formName.value'. The specific error message states: "Error: There is no Form ...

The curious case of jQuery.parseJSON() failing to decode a seemingly valid Json string on a Windows-based server

I am currently running a WordPress JavaScript function code on a Linux server that also includes a PHP function called "get_form_data". jQuery.ajax({ type: "POST", url: MyAjax.ajaxurl, data: {action: "get_fo ...

Tips for handling Google Spanner Date type in JavaScript

I am facing a challenge with Google Cloud Spanner as I work with multiple tables containing columns of type Date. While inserting entries with specified dates works fine, the issue arises when trying to retrieve these entries in the JavaScript frontend. Th ...

Error in Directive: NgControl Provider Not Found

I encountered an issue with my Directive while attempting to inject 'NgControl' and received a 'No provider for NgControl' error. Here is the structure of my File Directory: app folder |--directives folder |--myDirec ...

Learn how to dynamically add and remove a CSS class from an element using a scroll event in Angular 7

My goal is to create a navbar that gains a "fixed-top" class during scrolling and removes it when it reaches the top of the page. I've written the following script, but unfortunately, it's not working as expected. import { Component, OnInit, Af ...

The Node function is failing to produce a JSON object as expected

This particular file in my library is named verifyToken.js require('dotenv').config(); const CognitoExpress = require("cognito-express"); //Initializing the CognitoExpress constructor const cognitoExpress = new CognitoExpress({ cognitoUserP ...

"Exploring the power of Ajax: a guide to automatically refreshing the response every

I am struggling to understand why this snippet of code isn't working as expected. The div updates when using .html, but not with my custom script. In my setup, I have two files: index.php and test.php The index file looks like this: $(document).rea ...

Guide on converting JSON data into a PDF using TypeScript

I need to take JSON data and convert it into a PDF format when the PDF button is clicked in the UI. I have tried a few things but I'm struggling with binding the response to the PDF function. My goal is to display values from the "actualExpenses" arra ...

Adding an image to a React component in your project

I am currently working on an app that utilizes React and Typescript. To retrieve data, I am integrating a free API. My goal is to incorporate a default image for objects that lack images. Here is the project structure: https://i.stack.imgur.com/xfIYD.pn ...

Function not executing on button press in React.js

I am trying to trigger a function upon clicking a button, but unfortunately, nothing is happening. Despite adding a console.warn() statement inside the function, it doesn't seem to be logging anything. I've looked through similar Stack Overflow s ...

Retrieving every single .json file present in a specific folder

I'm working on developing an Android app that utilizes JSON data. Is there a method to establish a directory structure similar to this: http://......./jsons/*.json Or is there another way to append additional data into a JSON file (such as a.json) a ...

When running npm install, an ERESOLVE error message may appear indicating that a resolution could

Upon executing npm install, I encounter the following error message: code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: @angular-devkit/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d8baadb1b ...