Encountering an undefined property error while using Array.filter in Angular 2

hello everyone, I am currently faced with an issue while working on a project that involves filtering JSON data. When using the developer tools in Chrome, it keeps showing me an error related to undefined property.

 chart: JsonChart[] = [];
 charts: JsonCharts[] = [];

 getCharts() {
    this.iChartHttp.getCharts()
        .subscribe(
        charts => this.charts = charts, //return json object
        error => this.errorMessage = <any>error
        );
}

 if (this.chart_id != null) {
        this.getCharts();
         this.chart = this.charts.filter(charts => charts.id === this.chart_id)[0].series; // this like error occur.
    }

Revised Question:

I am encountering a problem where the JSON Array is not being retrieved from the Service, despite it working fine in another component.

iChartHttpService:

 getCharts(): Observable<JsonCharts[]> {
return this.http.get('assets/datas.json')
  .map((res: Response) => res.json())
  .do(data => console.log('server data:', data))  // debug
  .catch(this.handleError);
}

/**
* Handle HTTP error
*/
private handleError(error: any) {
// In a real world app, we might use a remote logging infrastructure
// We'd also dig deeper into the error to get a better message
const errMsg = (error.message) ? error.message :
  error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);

}

Answer №1

If the charts are null, make sure to place your filter logic after getting the results,

  getChartsData() {
        this.iChartHttp.getCharts()
            .subscribe((charts: any) => {
            this.charts = charts, //returning json object
            this.chart = this.charts.filter(charts => charts.id === this.chart_id)[0].series; 
            }, error => {
                error => this.errorMessage = <any>error
            });
    }

Answer №2

It seems like in order to properly utilize the javascript filter function, you should ensure that the series is being sent within it. Here's how you can update it:

if (this.chart_id != null) {
    this.getCharts();
    if (this.chart.length > 0) {
        this.chart = this.charts.filter(charts => {
            if (charts.id === this.chart_id) {
                charts[0].series;
            }
        })
    }
}

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

My applications are not firing the deviceready event as expected

Struggling to incorporate a cordova plugin into my vue.js project using vue-cordova. Specifically, I am attempting to utilize the open-native-settings plugin to access device settings on iOS or Android. While it works seamlessly in the demo app provided b ...

Creating animated effects through Javascript and CSS triggered by user events

As a beginner in javascript and CSS, I am experimenting with creating a simple animation that adjusts the transparency of an image when triggered by an event. However, I am facing an issue where the animation only works every other time the function is cal ...

Nesting placeholders is not permitted in i18n

I am attempting to implement Interpolation with Vue3 and vue-i18n version 9.3. However, when I try to pass arguments, I encounter the following error: Message compilation error: Not allowed nest placeholder 1 | Showing {{from}} to {{to}} of {{total}} ent ...

What is the better choice in NodeJS: using "return cb(..)" or first calling cb(..) and then returning?

Forgive me if this sounds like a silly question, but I'm curious about the implications of something: Whenever I encounter an error or need to complete a function flow, I follow certain instructions such as: if(err) { cb(err); // or for exampl ...

Leverage the Power of Mongoose Schema Across Various Files (mongoose)

I recently encountered an issue while trying to utilize my Permissions schema in two different files. The error message "Cannot overwrite 'example' model once compiled" keeps popping up. Query: How can I effectively employ my Permissions schema ...

Delete the tag that comes before

Is there a specific tag like: <p id="name" onclick="javascript:var ele=context(this);">sumtext here</p><br> <p id="name" onclick="javascript:var ele=context(this);">newtext here</p><br> <script ...

How can HtmlUnit be used to identify and address website pages that display errors?

I've encountered an issue while trying to access this Ajax page through my Java program using the HtmlUnit 2.15 API. It seems that the problem arises from a broken link to a missing file located here. This is the snippet of code I'm working with ...

Sending information from the parent component to the child Bootstrap Modal in Angular 6

As a newcomer to Angular 6, I am facing challenges with passing data between components. I am trying to launch a child component bootstrap modal from the parent modal and need to pass a string parameter to the child modal component. Additionally, I want t ...

Unable to conceal adjacent element when z-index is set as 1

I encountered an issue where a modal is overlapping another element, and the close button of the underlying element has a z-index of 1. Despite creating a new modal with its own close button, the original close button remains visible on top. I attempted t ...

Transform an array of objects into an object of objects while maintaining the interior structure

I am searching for a specific solution that I have not come across yet. If such a solution exists, I would greatly appreciate a link to it. Currently, my code looks like this: const obj = {"key": [ { "name": { "companyName": "Something" } }, { "otherT ...

Unlock the Power of Typography in React with Material UI Styled Components

Exploring the world of material UI is a new experience for me. I am currently in the process of creating a styled component using Typography. Below is what I have attempted so far: import styled from 'styled-components'; import { FormGroup, ...

Implementing the Applet Param Tag using JavaScript or jQuery

<applet id="applet" code="myclass.class"> <param name="Access_ID" value="newaccessid"> <param name="App_ID" value="newappid"> <param name="Current_Url" value="newticketurl"> <param name="Bug_ID" value="newbugid"&g ...

Can you pre-process ng-repeat variables?

When using ng-repeat to display the output in a div, I noticed that elements in the bCrumbs collection begin with a slash and space. For the first loop iteration, I would like to remove them. This is my code: <div ng-repeat="bCrumb in bCrumbs" id="{{b ...

Run a function from an alternate element

I have successfully created a grid with a button that enables me to control a timer. When I click on the start button in the grid on the home page, the timer begins counting the time. By using a service, I am able to determine whether the timer is active ...

Tips for effectively splitting arrays nested within an array using JavaScript

Here is an example of slicing an array to generate a new one: var array= [ [1,"dataA","dataB","dataC","dataD"...], [2,"dataA","dataB","dataC","dataD"...], [3,"dataA","dataB","dataC","dataD"...], [4,"dataA","dataB","dataC","dataD"...]... ...

Ways to retrieve a concealed DOM element from a background window

I have been struggling to display a button that is located in the background window using the jQuery code below, but unfortunately it's not functioning as expected. On my webpage, I have a hidden button that should only be visible when a user adds a ...

Ways to make a button blink using AngularJS

Currently working on an AngularJS SPA application where a button is present in the front-end HTML page. When this button is clicked, it triggers an operation which takes some time to complete. I want to inform the user that the operation is still in prog ...

choosing a section within a table cell

This seems like a simple task, but I'm encountering some difficulties $("#info-table tbody tr").each(function(){ $(this).find(".label").addClass("black"); }); .black{ font-weight:bold; } <script src="https://ajax.googleapis.com/ajax/libs/j ...

Struggling to retrieve JSON data within the code

Recently, I've been receiving a JSON data from Microsoft cognitive services but unfortunately, I'm encountering difficulties incorporating it into my code. Is there something that I might be doing incorrectly? I attempted different approaches su ...

An error occurs in TypeScript when attempting to reduce a loop on an array

My array consists of objects structured like this type AnyType = { name: 'A' | 'B' | 'C'; isAny:boolean; }; const myArray :AnyType[] =[ {name:'A',isAny:true}, {name:'B',isAny:false}, ] I am trying ...