Issue with Angular 2 data table search filter - The property 'first_name' is not found in the 'type {}'

Currently in my Angular-cli project, I have implemented the following code for a data table with a search filter. The tutorial referenced in the link below was used, leveraging loadsh. http://plnkr.co/edit/grhag1P85teN4ftggkms?p=preview

You can find the package link here: https://github.com/mariuszfoltak/angular2-datatable

While attempting to add a search filter, an error occurred in the updateData function: Property 'first_name' does not exist on type '{}'. Could this issue be related to TypeScript, lodash version, or something else?

export class UsersComponent implements OnInit {

    public users: any = [];
    public filteredData: any;
    public filterQuery = "";
    public rowsOnPage = 10;
    public sortBy = "first_name";
    public sortOrder = "asc";

    ngOnInit() {
        this.authService.getUsersList(userData).subscribe(data => {
            var res = data.response;
            this.users = this.users;
            this.filteredData = res.data;
        });
    }

    public updateData(query:string) {
        if(query) {
            this.filteredData = _.filter(this.users, (a)=>a.first_name.indexOf(query)>=0);
        } else {
            this.filteredData = this.users;
        }
    }
}

Below is the snippet from my package.json file showcasing the lodash version:

"dependencies": {
  "angular2-datatable": "^0.6.0",
  "lodash": "^4.17.4",
},
"devDependencies": {

  "@types/lodash": "^4.14.50",
  "typescript": "~2.0.3"
}

Answer №1

It seems like the error occurred in your IDE, specifically a TypeScript error. The issue is related to the fact that your users array is of type any, and TypeScript cannot detect the first_name property within the type that lodash likely returns as an empty object {} due to the unspecified type of the users array. It's considered best practice to always create a class to represent the data, for example:

export class User {
    public first_name: string;
    /* And other data from your database */
}

/* In your component */
public users: Array<User> = [];

By defining a class, you can maintain clean and organized code. If you prefer not to create classes, you can use the as syntax along with parentheses as shown below.

this.filteredData = _.filter(this.users, (a)=>(a as any).first_name.indexOf(query)>=0);

Additionally, if you want to use the type any for arrays, you can specify it using any[] or Array<any>.

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

Utilizing react js computed property to retrieve a state value: A guide

I recently developed a fading text component where the header fades in and out using transition opacity CSS and a visibility state. To simplify my code, I decided to create a fading text group component that can handle multiple fading texts at once. My goa ...

Tips for utilizing onclick in React Threejs with a loaded GLTF model

After loading the GLTF file successfully and admiring its appearance, a desire arises to interact with it by clicking on it and extracting specific information, such as a uuid. However, upon attempting this interaction, an error is triggered stating "TypeE ...

Tips for updating the color of the mat-paginator's border at the bottom

Is there a way to change the border bottom color of my mat-paginator when an option is selected? It currently defaults to purple, but I would like to customize it. Any suggestions? Click here for an example of the current purple border on Mat-paginator. ...

What's the best way to organize Python objects for optimal JSON serialization?

Recently transitioning from JavaScript to Python, I am facing a challenge in understanding how to effectively communicate between client and server using JSON. Specifically, I am struggling to find the equivalent of an easily jsonifyable object attribute i ...

Errors are encountered when attempting to run the React project command

I attempted to start my React.js project, which utilizes typeScript and webpack. However, I ran into numerous errors when executing the command npm run dev (please refer to the snippet attached below). Here is what I attempted: Removed the node_modules d ...

Establishing the folder organization for Express Handlebars

I work with NodeJs, Express, and Handlebars. The main file for my server is named app.js const express = require('express'); const exphbs = require('express-handlebars'); const app = express(); app.engine('handlebars', ex ...

The intricacies of how Node.js handles asynchronous execution flow

I wanted to ask about the best approach for displaying data retrieved from MySQL. Do you think this workflow is correct? app.get('/demo/:id', function(req, res) { var query = csql.query('SELECT * FROM table_videos WHERE id=? LIMIT 1' ...

What is the best way to categorize variables?

How can I organize variables together: export let findbyc$: Observable<Object>; export let findbyi$: Observable<Object>; export let findbyo$: Observable<Object>; export let findbyob$: Observable<Object>; I would like to group them ...

JavaScript may not display height as anticipated

Currently, I am experimenting with JavaScript in order to achieve a website section that is 100% the height of the screen minus the "nav" bar. Imagine it as having two visible components - the first one being large and the second one small at the bottom. ...

Iterate over the items stored in localStorage and display a particular value when clicked

For my library project, I am trying to create a shopping cart feature. The issue I'm facing is that when I click on a specific book, I cannot add it to another localStorage. This is my html <!--Knjige--> <div class="container grid" id=&ap ...

Tips for assigning data from an AJAX response to a variable

Using jQuery and the code provided, there seems to be an issue with variable scope when some_condition is false. The error "items is not defined" indicates this problem. The goal is to set the result variable to the AJAX response data in order to use it o ...

Tips on eliminating the warning that arises when adding Bootstrap to the styles.css file in Angular

After adding Bootstrap v4.1.0 to my Angular Project's styles.css, I encountered a warning in the console. [WDS] Warnings while compiling. ./src/styles.css (./node_modules/@angular-devkit/build-angular/src/angular-cli-files/plugins/raw-css-loader.j ...

How can I dispatch multiple actions simultaneously within a single epic using redux-observable?

I am a newcomer to rxjs/redux observable and have two goals in mind: 1) enhance this epic to follow best practices 2) dispatch two actions from a single epic Many of the examples I've come across assume that the API library will throw an exception ...

Mixing colors in THREE.js vertex shader based on height levels

How can I change the color of the mesh to blue only when the height is zero? Currently, I am using a mixture of colors: https://i.sstatic.net/x3s4d.png The issue with this blending method is that it lacks precision. I want the color blue to appear only ...

Is there a way to automatically scroll two identical vertical long images one after the other in a continuous loop?

My goal is to replicate the effect seen on the website , where a vertical image moves downwards and then repeats by starting from the bottom once it reaches the top. Essentially, there are two images moving downward in this loop. I attempted to find a sui ...

Utilizing JSON API data to populate Leaflet maps

I am currently working on fetching JSON data from an API call, extracting the latitude, longitude, and name variables to create a GeoJSON array, and then displaying it on a Leaflet map. Despite not encountering any errors in the console, the geojson appea ...

typescript create a type from a schema

Recently, I received an auto-generated GraphQL schema mapping that looks like this: export const generatedSchema = { query: { __typename: { __type: 'String!' }, account_sample: { __type: '[account_sample!]!', __arg ...

Perform an AJAX call from the main file after inserting data using AJAX beforehand

I am in need of assistance with a question I have. On a page, an AJAX function is executed after the page finishes loading, creating a table in PHP that contains two buttons: one for changing passwords and the other for deleting. This table is then injecte ...

Creating a linear video playback system

Having an issue with my code in Chrome where auto play is enabled, but the video won't play. I have a loop set up to play each video one after the other, but first things first - how do I get this video to start playing? If there's a pre-made so ...

The error message "Unable to iterate over undefined property in Node.js using EJS and JavaScript" popped up

I've been struggling with the error "Cannot read property 'forEach of undefined" for two days now and I just can't seem to figure out the problem. Any help would be greatly appreciated. Here is the code: bruidstaart.js page where I am tryin ...