Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Tuesday 21 March 2023

Mastering Data Filtering with Complex Objects: Strategies and Techniques


Mastering Data Filtering with Complex Objects: Strategies and Techniques


Hi Everyone, The filter logic is a mechanism that allows you to search and retrieve specific data from a larger dataset. The filter function takes two arguments: the data to filter and a filter parameter that defines the search criteria. The function returns a subset of the original data that matches the filter criteria.So lets understand how we can acheive "Data Filtering with Complex Objects".

In the case of the Angular Material table, the filter logic is used to search for specific data in a table by applying a search filter to one or more columns. When the user enters a search query, the filter logic is triggered and filters the table data based on the search criteria. The filtered data is then displayed in the table.

The filter logic can be implemented in many ways, depending on the specific use case.
Now consider this JSON array which contains nested array.


[

{

deviceUUID: ‘80a9b8a2–3a2c’,

ipAddress: ‘2.2.2.67’,

deviceParameter: {

deviceName: ‘device44’,

unitIdentifier: 1,

port: 502,

},

isConnected: false,

isSerial: false,

details: null,

Type: ‘Ethernet’,

},

{

deviceUUID: ‘80a9b8a2–3a2c’,

ipAddress: ‘2.2.2.67’,

deviceParameter: {

deviceName: ‘device46’,

unitIdentifier: 1,

port: 503,

},

isConnected: false,

isSerial: false,

details: null,

Type: ‘Ethernet’,

},

{

deviceUUID: ‘80a9b8a2–3a2c’,

ipAddress: ‘2.2.2.67’,

deviceParameter: {

deviceName: ‘device48’,

unitIdentifier: 1,

port: 505,

},

isConnected: false,

isSerial: false,

details: null,

Type: ‘Ethernet’,

}

];




So if our requirement says that filter the object on ‘device name’ or ‘port’ that is not quite possible because that mat-filter is works with straight forward object but we can also achieve this things first understand how we can do that

The inner object search is different because it requires accessing a nested property within each object of an array, whereas other searches involve searching for a property directly in each object of the array. This requires a different approach to extract the nested property and perform the search.

So here we use ‘ filterPredicate’ to search nested object : The filterPredicate is used to search nested objects in a mat-table because the default filter behaviour in Angular Material only works on flat objects with simple properties. When dealing with more complex data structures like nested objects, we need to write their own custom filtering logic to extract the nested data they want to filter on. The filterPredicate function provides a way to do this by allowing us to write own filtering logic based on the nested data structure of their data source.

So lets begin with our example.


first create a one project which have preinstall angular material and all dependencies that is required to run angular mat-table to run

2. Here is my app.component.html code to declare mat-table

<mat-label>Filter</mat-label>

<input matInput (keyup)=”applyFilter($event)” placeholder=”Ex. ium” #input>

<table mat-table [dataSource]=”dataSource” matSort matSortActive=”deviceName” matSortDirection=”asc” matSortDisableClear>

<ng-container matColumnDef=”deviceName”>

<th mat-header-cell *matHeaderCellDef mat-sort-header> Device Name </th>

<td mat-cell *matCellDef=”let device”> {{device.deviceParameter.deviceName}} </td>

</ng-container>

<ng-container matColumnDef=”unitIdentifier”>

<th mat-header-cell *matHeaderCellDef> Unit Identifier </th>

<td mat-cell *matCellDef=”let device”> {{device.deviceParameter.unitIdentifier}} </td>

</ng-container>

<ng-container matColumnDef=”port”>

<th mat-header-cell *matHeaderCellDef> Port </th>

<td mat-cell *matCellDef=”let device”> {{device.deviceParameter.port}} </td>

</ng-container>

<tr mat-header-row *matHeaderRowDef=”displayedColumns”></tr>

<tr mat-row *matRowDef=”let row; columns: displayedColumns;”></tr>

</table>

3. Replace the component.ts code with this

import { Component } from ‘@angular/core’;

import { MatTableDataSource } from ‘@angular/material/table’;

export interface Device {

deviceUUID: string;

ipAddress: string;

deviceParameter: {

deviceName: string;

unitIdentifier: number;

port: number;

};

isConnected: boolean;

isSerial: boolean;

details: any;

Type: string;

}

const DEVICE_LIST: Device[] = [

{

deviceUUID: ‘80a9b8a2–3a2c’,

ipAddress: ‘2.2.2.67’,

deviceParameter: {

deviceName: ‘device44’,

unitIdentifier: 1,

port: 502,

},

isConnected: false,

isSerial: false,

details: null,

Type: ‘Ethernet’,

},

{

deviceUUID: ‘80a9b8a2–3a2c’,

ipAddress: ‘2.2.2.67’,

deviceParameter: {

deviceName: ‘device46’,

unitIdentifier: 1,

port: 503,

},

isConnected: false,

isSerial: false,

details: null,

Type: ‘Ethernet’,

},

{

deviceUUID: ‘80a9b8a2–3a2c’,

ipAddress: ‘2.2.2.67’,

deviceParameter: {

deviceName: ‘device48’,

unitIdentifier: 1,

port: 505,

},

isConnected: false,

isSerial: false,

details: null,

Type: ‘Ethernet’,

}

];

@Component({

selector: ‘app-root’,

templateUrl: ‘./app.component.html’,

styleUrls: [‘./app.component.css’]

})

export class AppComponent {

title = ‘MaterialDesign’;

displayedColumns: string[] = [‘deviceName’, ‘unitIdentifier’, ‘port’];

dataSource = new MatTableDataSource<Device>(DEVICE_LIST);

constructor() {

// this.dataSource = new MatTableDataSource<Device>(DEVICE_LIST);

this.dataSource.filterPredicate = (data: Device, filter: string) => {

const searchString = filter.trim().toLowerCase();

return data.deviceParameter.deviceName.toLowerCase().includes(searchString) ||

data.deviceParameter.port.toString().toLowerCase().includes(searchString);

};

}

applyFilter(event: Event) {

const filterValue=(event.target as HTMLInputElement).value;

this.dataSource.filter = filterValue.trim().toLowerCase();

}

}




4. Replace the app.module.ts file with following code :


import { NgModule } from ‘@angular/core’;

import { BrowserModule } from ‘@angular/platform-browser’;

import { AppRoutingModule } from ‘./app-routing.module’;

import { AppComponent } from ‘./app.component’;

import { BrowserAnimationsModule } from ‘@angular/platform-browser/animations’;

import { MatSlideToggleModule } from ‘@angular/material/slide-toggle’;

import { MatButtonModule } from ‘@angular/material/button’;

import { MatTableModule } from ‘@angular/material/table’;

import { MatPaginatorModule } from ‘@angular/material/paginator’;

import { MatSortModule } from ‘@angular/material/sort’;

import { MatFormFieldModule } from ‘@angular/material/form-field’;

@NgModule({

declarations: [

AppComponent,

],

imports: [

BrowserModule,

AppRoutingModule,

BrowserAnimationsModule,

MatSlideToggleModule,

MatButtonModule,

MatTableModule,

MatPaginatorModule,

MatSortModule,

MatFormFieldModule

],

providers: [],

bootstrap: [AppComponent]

})

export class AppModule { }

Now understand how this filterPredicate function works. please again review this code


constructor() {

this.dataSource.filterPredicate = (data: Device, filter: string) => {

const searchString = filter.trim().toLowerCase();

return data.deviceParameter.deviceName.toLowerCase().includes(searchString) ||

data.deviceParameter.port.toString().toLowerCase().includes(searchString);

};

}

applyFilter(event: Event) {

const filterValue=(event.target as HTMLInputElement).value;

this.dataSource.filter = filterValue.trim().toLowerCase();

}

The function is being assigned to the filterPredicate property of a MatTableDataSource object.

It takes two arguments: data and filter. data represents a single element in the data source, while filter is the value entered by the user to filter the data.

searchString is a variable that is created by trimming any whitespace and converting the filter string to lowercase.

The function returns a boolean value that determines whether or not the data object should be included in the filtered data source. It does this by checking if the lowercase deviceName or lowercase port of the deviceParameter object of the data object includes the searchString.

If the searchString is found in either deviceName or port, the function returns true, indicating that the data object should be included in the filtered data source.

If the searchString is not found in either deviceName or port, the function returns false, indicating that the data object should be excluded from the filtered data source.

Please feel free to check out my GitHub repository at the following link, where you can find the code for the NestedObjectFilterMatTable:

Filter Nested Complex object

I would greatly appreciate it if you could take a look at it and let me know if you have any feedback or suggestions. Thank you very much for your time and consideration.

Friday 10 March 2023

Missing Helper ‘__spreadArray’:Upgrading ‘tslib’ Required or This syntax requires an imported helper named ‘__spreadArray’ which does not exist in ‘tslib’. Consider upgrading your version of ‘tslib’.ts

Fixing Console Error: Troubleshooting Loom Chrome Extension for Running Projects

 As the colors of Holi fade, I extend my warmest greetings to all. May you be blessed with good health and happiness in the days ahead.

Today, we’ll explore the purpose of the ‘__spread’ array and why it causes errors in TypeScript (while it works fine in JavaScript). I’ll provide an example to illustrate the issue and then share the solution I found while developing this feature in TypeScript.

Let’s start by discussing the purpose of the __spreadArray function.

The ‘__spreadArray’ helper function is used in TypeScript code that uses the spread operator (…) on an array. The spread operator is used to “spread” the elements of an array into a new array.

However, when using the spread operator with an empty array, it can sometimes cause issues in TypeScript. For example, consider the following code:

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

const combinedArr = […arr1, …arr2];

This code will work fine in JavaScript, but in TypeScript, it will produce an error,

error TS2532: Object is possibly ‘undefined’.

Now that we have a better understanding of the __spreadArray function, we can delve into the reasons why this error occurs specifically in TypeScript.

This error occurs because TypeScript is not sure if the arrays being spread are empty or not. To avoid this issue, the ‘__spreadArray’ helper function can be used instead of the spread operator when combining arrays. The ‘__spreadArray’ function takes two arguments: the first is the initial array, and the second is the array to be added.

Now, let’s move on to the solution. There are two ways to resolve this issue when working with TypeScript and Angular.

  1. By importing __spreadArray in our .ts file: Here is an example of how ‘__spreadArray’ can be used to combine arrays safely in TypeScript:
    import { __spreadArray } from ‘tslib’;

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

const combinedArr = __spreadArray(__spreadArray([], arr1), arr2);

In this example, we use ‘__spreadArray’ to create a new array by first creating an empty array with ‘__spreadArray([], arr1)’, then adding ‘arr1’ to it, and finally adding ‘arr2’ to the result. The ‘__spreadArray’ function ensures that TypeScript understands that the first argument is an array and not undefined, which avoids the error that was produced earlier.

Now come to second solution.

2. By installing tslib library in our angular node module by following command.

npm install tslib@latest

Alternatively, if you are using a package manager other than npm, you can upgrade tslib using the appropriate command for your package manager.

Once you have upgraded tslib, you should no longer see this error message.

I hope you found this article informative and useful! If you know someone else who might be struggling with the same error, please share this article with them so they can benefit from this solution too. Thank you for reading!



Tuesday 21 February 2023

what is crawl request

 


A crawl request is a request made by a webmaster or website owner to a search engine's crawler to visit and crawl a specific web page or URL on their website.


Search engine crawlers (also known as spiders, bots or robots) are programs that scan the web, discovering and indexing new pages, and updating the search engine's index with new or updated content. When a website is crawled, the search engine's crawler visits the website and analyses the content of the pages to determine what the website is about and how relevant it is to specific search queries.


A crawl request can be useful for ensuring that a new or updated page on your website is indexed quickly by search engines. If you have made changes to a page that you want search engines to know about, you can submit a crawl request to the search engine so that it will visit the updated page and reindex it. This can help to ensure that the updated content is reflected in search results as quickly as possible.

It's worth noting that submitting a crawl request does not guarantee that the search engine will crawl your page immediately, but it can speed up the process. In general, search engines will crawl pages based on their own algorithms and schedule, so it's important to ensure that your website is optimized for search engines and that you regularly publish new and relevant content.

Friday 17 February 2023

An Introduction to JavaScript: The Language That Powers the Web

 Introduction:

JavaScript is one of the most popular programming languages in the world, and for good reason. It is the primary language used to create interactive web pages and dynamic user interfaces. In this blog post, we will give you a brief introduction to JavaScript and explain why it is such an important language for web development.

Section 1: What is JavaScript? JavaScript is a high-level, object-oriented programming language that is primarily used to create dynamic, interactive web pages. It was first created in 1995 by Brendan Eich and is now one of the three core technologies of the World Wide Web, along with HTML and CSS.

Section 2: Why is JavaScript important? JavaScript is important because it allows web developers to create interactive and dynamic websites. With JavaScript, you can create pop-ups, animations, interactive forms, and much more. It is also widely used on the server-side, using frameworks like Node.js, allowing developers to create full-stack web applications.

Section 3: What can you do with JavaScript? JavaScript is a versatile language that can be used for a wide range of tasks. Here are just a few examples:

  • Create interactive user interfaces: JavaScript can be used to create dynamic user interfaces that respond to user input and interactions.
  • Validate user input: JavaScript can be used to validate user input in forms, ensuring that data is entered correctly.
  • Create animations: With JavaScript, you can create animations and visual effects that add an extra layer of interactivity to your web pages.
  • Make API calls: JavaScript can be used to make API calls to retrieve data from servers and display it on a web page.
  • Build web applications: Using frameworks like React, Vue, or Angular, you can use JavaScript to build powerful web applications that run on the client and server side.

Section 4: How do you learn JavaScript? Learning JavaScript is relatively easy, especially if you already have some experience with programming. There are many resources available, including online courses, tutorials, and books. Some popular online resources for learning JavaScript include Codecademy, FreeCodeCamp, and W3Schools.

Conclusion: JavaScript is an essential language for web development, allowing developers to create dynamic and interactive web pages. With the rise of full-stack web development, JavaScript has become even more important, as it is now used on both the client and server sides. If you are interested in web development, learning JavaScript is a great place to start.

AdSense

The Ultimate Guide to Interceptors: Understanding Their Power and Functionality

  The Ultimate Guide to Interceptors: Understanding Their Power and Functionality An interceptor is a service that can intercept HTTP reques...

Follow