Steps for Adding a JSON Array into an Object in Angular

Here is a JSON Array that I have:

0: {name: "Jan", value: 12}
1: {name: "Mar", value: 14}
2: {name: "Feb", value: 11}
3: {name: "Apr", value: 10}
4: {name: "May", value: 14}
5: {name: "Jun", value: 12}
6: {name: "Jul", value: 10}
7: {name: "Aug", value: 14}
8: {name: "Sep", value: 11}

I am looking for a way to insert this response into the data object within the lineData array provided below. The JSON data is sourced from a local JSON file and needs to be incorporated into the linedata array.

The desired format is as follows:

public lineData = [{
    data: [
      { name: 'Jan | 2018', value: 12 },
      { name: 'Jan | 2018', value: 11 },
      { name: 'Jan | 2018', value: 14 },
      { name: 'Jan | 2018', value: 10 },
      { name: 'Jan | 2018', value: 14 },
      { name: 'Jan | 2018', value: 8 }
    ],
    name: 'Component A',
    id: '1'
  }]

The relevant files are listed below:

chart.json

[
    { "name": "Jan", "value": 12 },
    { "name": "Mar", "value": 14 },
    { "name": "Feb", "value": 11 },
    { "name": "Apr", "value": 10 },
    { "name": "May", "value": 14 },
    { "name": "Jun", "value": 12 },
    { "name": "Jul", "value": 10 },
    { "name": "Aug", "value": 14 },
    { "name": "Sep", "value": 11 }
]

chart.ts

export interface IChart {
    name: string;
    value: number;
    //id?: string;
}

chart.service.ts

import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { Injectable, OnInit } from "@angular/core";
import { IChart } from '../chart';

@Injectable({
    providedIn: 'root'
})

export class ChartDataService {

    private url: string = "assets/data/chartData.json";

    constructor(private httpClient: HttpClient) { }
    
    getChartData(): Observable<IChart[]>  {
        return this.httpClient.get<IChart[]>(this.url);
    }
}

chart.component.ts

import { from } from 'rxjs';
import { ChartDataService } from './../../services/chart-data.service';
import { Component, Input, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { IChart } from './../../chart';

@Component({
  selector: 'app-charts',
  templateUrl: './charts.component.html',
  styleUrls: ['./charts.component.css']
})
export class ChartsComponent implements OnInit {

  @Input() chartTitle: string;
  @Input() dataSetType: any;
  public chartDataList : IChart[];

  constructor(private chartDataService: ChartDataService) { }

  ngOnInit() {

    this.chartDataService.getChartData().subscribe( data => {

     //need a solution for here

      }
    ) 
  }
}

Answer №1

Start by defining the lineData model

export interface lineDataModel {
  data: any[],
  name: string,
  id: string
}

In your chart.component.ts, initialize the lineData array

lineData: lineDataModel[] = [];

If the result returned by the getChartData() function in your charDataService matches the one in your initial JSON array.

this.chartDataService.getChartData().subscribe( data => {
  lineData.data.push(data);
}

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

Transforming this JavaScript code to be less intrusive by implementing an event listener for an unidentified ID

As I work on enhancing the functionality of this user interface, I've encountered a challenge with two tabs that require a proper event listener to ensure my JavaScript functions smoothly. This obstacle has been hindering my progress, but as I delve i ...

No elements can be located within the iframe as per Cypress's search

I've been attempting to access elements within an iframe using the guidance provided in this article here, but I'm facing an issue where Cypress is unable to locate anything within the iframe. Below is a snippet of my test code: describe('s ...

Is there a way to compare the elements of an array with those of another array containing nested arrays in order to identify matching results?

Every user in our database has specific skills assigned to them. We maintain a list of available skills with unique IDs. The objective is to filter users based on the skill we are interested in, like displaying all Janitors. We are utilizing Vue.js and im ...

Deactivating a form field depending on a selected radio button in Angular 2

If I have two radio buttons, with a click function called localClick for the first button to give value 1 and the second button to give value 2. <div class="ui-g-12"><p-radioButton name="group1" value="Local" (click)=localClick(1) label="Local"&g ...

What causes the failure of `click()` on a WebElement?

I am currently utilizing protractor within an angular application. The page model I have is structured as follows: export interface TileElement { idx: number; icon: string; title: string; element: WebElementPromise; } getModels() { //used as wfc. ...

Issue occurs when nested functions prevent the data() variable from updating

As a newcomer to VUE, I may not be using the right terminology so bear with me. I'm attempting to update a variable that is defined in the script tag's "data()" function. The issue arises when trying to change the value of a variable within the ...

Tips for retaining form inputs without the need for a submit event when the page is reloaded or refreshed

I have a form on a page with multiple text inputs In addition to the form, I have implemented Zend pagination to allow users to select results. However, when using Zend paginate, the user's form inputs are lost because it is not submitted. Since th ...

What is the best way to transfer data to another PHP file using AJAX?

Being new to ajax and lacking significant knowledge about it, I have created two PHP files - six.php and six-cuf.php. Upon user input in six.php and submission, this will trigger a call to six-cuf.php using ajax for the calculation. However, while executi ...

Using Paper.js to access and manipulate document.body.style.opacity within a paperscript

My website is essentially one large canvas image. Currently, the body fades in when loaded using this code: <body onLoad="document.body.style.opacity='1'"> However, I want to initiate this fade within my paperscript because sometimes the ...

Troubleshoot: Issue with Navbar Dropdown Expansion on Bootstrap Sass 3.3.6 with JavaScript

Beginner: Bootstrap Sass 3.3.6 - Incorporating Javascript - Issue with Navbar Dropdown Not Expanding application.html.erb Head: <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %> ...

How can I conditionally disable a button in Vue.js using an if statement?

Can someone help me figure out why all my buttons are getting disabled when I only want one to be disabled? Here is the code where I created a counter with vue.js: <body> <div id="app"> <button @click="co ...

increase the count by one every second using setInterval

I need my sHand to increase by 6 every second, but currently it only increases once. When I try something like this.sHand++, it works fine and increases by 1 degree per second. However, I want it to increase by 6 instead of 1. Any solutions? data:{ ...

Struggling with creating a generic TypeScript structure?

My goal is to manipulate data structured like this: const exampleState = { elements : { element1: { values: { value1: 10, value2: 10, }, elementDetails : { detail1 : { values: { value1: ...

Tips for setting a threshold in a highcharts ng chart

I am struggling with setting the threshold to zero on a simple line chart using Highchart ng. According to the Highcharts API, the property should be plotOptions.series.threshold. However, despite following advice from this source, I can't seem to get ...

Finding the precise top offset position with jQuery upon scrolling – a step-by-step guide

I need help with detecting the offset top of a TR element when it is clicked. It works fine initially, but once the page is scrolled, the offset().top value changes. How can I resolve this issue? $(function() { $('tr').click(function() { ...

Confirm whether the Iterator type is the same as the AsyncIterator type

Is there a clever JavaScript technique to differentiate between Iterator and AsyncIterator without initiating the iteration process? I'm attempting to create a type checker like this: function isAsyncIterator<T>(i: Iterator<T> | AsyncIter ...

AngularJS: Functions may return false due to the asynchronous nature of services

Template Overview: <div data-ng-if="budgetSummaryExists()"> <span>You currently have no budget.</span> <button type="button" class="btn btn-danger" data-ng-click="setRoute('budgets')">Creat ...

An array variable marked as mat-checked contains the total sum

Currently, I am utilizing mat-checked to calculate a total sum from an Array. The issue arises when the number of items in my array varies, triggering an error: ERROR TypeError: Cannot read property 'isChecked' of undefined Is there a way to ...

Transforming a set of datetime objects into a specific JSON structure

I am currently utilizing a specific JavaScript Calendar tool to display days with scheduled events. The format this calendar tool requires for data input is as follows: { "2019": { "7": { "2": [ {} ], "13": [ {} ...

Having trouble converting JSON string into map using Jackson in Java

I am having an issue with this snippet of code where I am attempting to convert a JSON string into a map. String json = "[{'code':':)','img':'<img src=/faccine/sorriso.gif>'}]"; ObjectMapper mapper = new Objec ...