Angular 2 TypeScript: How to effectively sort an array

Iā€™m currently exploring how to implement array filtering in Angular 2 with TypeScript. Specifically, I am trying to filter data for a search bar in Ionic 2. While the list in the template successfully displays the data, I am encountering difficulty getting the filtering functionality to work.

initializeItems(i:number) {
 this.http.get('https://maps.googleapis.com/maps/api/place/details/json?placeid='+this.placeid+'&key=AIzaSyBPi-ayuvkTht4wddCcvcy0l2wIBdT9P2w').map(res => res.json()).subscribe(data => {
  this.locations[i]._detail = data.result;

  this.names.push([
    {
      name: this.locations[i]._detail.name,
      adress: this.locations[i]._detail.formatted_address,
      phone: this.locations[i]._detail.formatted_phone_number
    }
  ]);

  this.items = this.names;
  console.log(this.items);
 });
}

getItems(ev) {
  this.items = this.names;
  console.log(this.items);
  // set val to the value of the ev target
  var val = ev.target.value;

  // if the value is an empty string don't filter the items
  if (val && val.trim() != '') {
    this.items = this.items.filter((item) => {
      return (item.name.toLowerCase().indexOf(val.toLowerCase()) > -1);
    })
  }
}

Upon entering text into the search bar, I encounter the following error message.

https://i.sstatic.net/3Kav3.png

Answer ā„–1

I have successfully resolved the issue.

  1. Converted the keys to strings within the object
  2. Inserted [0] in the return statement
  3. Transformed the array into orginames and assigned items = orginames, preventing an empty array when searching and deleting a word again.

initializeItems(i:number) {
this.http.get('https://maps.googleapis.com/maps/api/place/details/json?placeid='+this.placeid+'&key=AIzaSyBPi-ayuvkTht4wddCcvcy0l2wIBdT9P2w').map(res => res.json()).subscribe(data => {
  this.locations[i]._detail = data.result;


  this.orginames.push([
    {
      "name": this.locations[i]._detail.name,
      "address": this.locations[i]._detail.formatted_address,
      "phone": this.locations[i]._detail.formatted_phone_number
    }
  ]);

  this.items = this.orginames;
  // this.orginames.push(this.locations[i]._detail.name);

});
console.log(this.items);

}

getItems(ev) {
  this.items = this.orginames;
  //console.log(this.items);
  // set val to the value of the ev target
  var val = ev.target.value;

  // if the value is an empty string don't filter the items
  if (val && val.trim() != '') {
    this.items = this.items.filter((item) => {
      return (item[0].name.toLowerCase().indexOf(val.toLowerCase()) > -1);
    })
  }
}

Answer ā„–2

It seems like your implementation of the push method is incorrect. Make sure you are pushing the object into an array, not another array. If you need to add multiple items, consider using the spread operator.

  this.items.push(
    {
      item: this.inventory[i]._info.name,
      description: this.inventory[i]._info.description,
      price: this.inventory[i]._info.price
    }
  );

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

I can't figure out why I'm getting the error message "Uncaught ReferenceError: process is not defined

I have a react/typescript app and prior to updating vite, my code checked whether the environment was development or production with the following logic: function getEnvironment(): "production" | "development" { if (process.env.NODE_E ...

Issue with React hook forms and shadcn/ui element's forwardRef functionality

Greetings! I am currently in the process of creating a form using react-hook-form along with the help of shadcn combobox. In this setup, there are two essential files that play crucial roles. category-form.tsx combobox.tsx (This file is utilized within ...

There seems to be an issue in Angular as it is unable to retrieve /

I'm encountering an issue with my simple application where I am receiving the error message "Cannot GET /." Also, in the console, I see this error: TypeError: Cannot read property 'checked' of null at Object.SL_BBL_locer. I'm unsure ab ...

How can Angular 2 effectively keep track of changes in HTTP service subscriptions? Calling the method directly may result in

After making a call to the authentication service method that checks the validity of the username and password, as well as providing an authentication token, I encountered an issue. When attempting to display the value obtained from calling the getAuthData ...

Monitoring changes in a variable's value within an Angular 6 component

Within a page component, there exists an array; The array has new elements added to it in different locations within the component (in the createMessage() method and inside the subscriber of getIncomingMessagesStream()); Each time a new element is added to ...

Why does Typescript not enforce a specific return type for my function?

In my custom Factory function, I need to return a specific type: type Factory<T> = () => T; interface Widget { creationTime: number; } const createWidget: Factory<Widget> = () => { return { creationTime: Date.now(), foo: &a ...

Managing errors with async/await in an Angular HttpClient function

I have been experimenting with an async/await pattern to manage a complex scenario that could potentially result in "callback hell" if approached differently. Below is a simplified version of the code. The actual implementation involves approximately 5 co ...

Having difficulty overriding the Content-type in http.put while using Angular RC2

I'm encountering an issue in the latest version of rc2 that didn't exist in older versions and I'm unsure if it's a bug or something I'm doing wrong. The problem arises when making a http.put request where I need to set Content-ty ...

What is the best way to transform a synchronous function call into an observable?

Is there a conventional method or developer in RxJS 6 library that can transform a function call into an observable, as shown below? const liftFun = fun => { try { return of(fun()) } catch (err) { return throwError(err) } ...

When applying multiple classes with NgClass, use the property name instead of the class content

I am facing a challenge trying to add multiple classes (in this case 2) to a custom component that includes a list item component from MDBootstrap: App.module.ts <custom-list-component size="w-50"> <custom-list-item-component href="#">lis ...

Creating intricate structures using TypeScript recursively

When working with Angular and TypeScript, we have the power of generics and Compile-goodness to ensure type-safety. However, when using services like HTTP-Service, we only receive parsed JSON instead of specific objects. Below are some generic methods that ...

How can I convert the date format from ngbDatepicker to a string in the onSubmit() function of a form

I'm facing an issue with converting the date format from ngbDatepicker to a string before sending the data to my backend API. The API only accepts dates in string format, so I attempted to convert it using submittedData.MaturityDate.toString(); and su ...

I'm struggling to find a solution to this pesky TypeScript error that keeps popping up in the button component's styling. How can

An error related to style is appearing: <Button style = No overload matches this call. Overload 1 of 3, '(props: { href : string; } & { children?: React Node; classes?: Partial<Button Classes> | undefined; color?: "primary" | ...

What is the best way to compare two sets of arrays and generate a new one with unique key-value pairs?

I have two arrays and I want to extract specific key-value pairs from each and combine them into a new array, handling duplicate entries. First Array : [ {id: 2, name: "HSBC", status: "YES"}, {id: 3, name: "Morgan Stanley&quo ...

The generics in TypeScript for Parameters<URLS[T]> and the corresponding URLS[T] are not compatible

In the code below, I am encountering a type error: const urls = { inviteNewUser: ({teamId, intent = 'invite'}: {teamId: string; intent?: Intent}) => `/magic-link?intent=${intent}&teamId=${teamId}`, resetPassword: ({intent = 'r ...

Angular 11 - Binding Data to an Array Element

Currently, I am attempting to apply data-binding to specific properties of an element categorized as Ripe: export interface Ripe{ version: string; data_call_status: string; cached: boolean; data: { is_less_specific: boolean, ...

Angular 2 is encountering issues with reading and displaying unicode characters (ud83dude31 or u0C28u0C3E) from the http response onto the user

My current task involves extracting unicode data from an http response, specifically for emojis. The response is in the form of a property-value pair within an object, with the message content being presented as JSON data ("messageContent":"hello \&bs ...

What distinguishes the ///<reference path="..."/> from an import statement?

Initially, when I try to import React in my code, the TypeScript compiler displays an error saying 'can not find module react'. However, after adding /// before the import statement, the problem is resolved. Interestingly, I later discovered tha ...

Comparing two string dates in mongoose: A guide

I am trying to retrieve data between two specific dates in my Schema. transactionDate : String Here is the function I am using to get data between two dates: async getLogsByDate(start, end) { return await this.logModel .find({ date: { $gte: sta ...