简体   繁体   中英

Typescript/Angular: Filter array of objects

I have an array of objects.My object has a "category" attribute. I want to filter the array of objects to return only objects with the "tech" category".

The error being thrown is "filter" does not exist on type {}

stocks-list.ts

import { Stock } from './Stock';

export const STOCKS: any[] = [
  { id: 11, symbol: 'AAPL', name: 'Apple', category: 'Tech' },
];

stock.service.ts

import { Injectable } from '@angular/core';
import { Stock } from './Stock';

import { STOCKS } from './stocks-list';

@Injectable({
  providedIn: 'root'
})


export class StockService {


  constructor() { }
  techStocks: Stock[];
  getTechStocks(): Stock[] {
    this.techStocks = STOCKS;


    return this.techStocks.filter(xx => xx.category = 'Tech');
  }
}

You just need to replace xx.category = 'Tech' (who update) by xx.category === 'Tech' (who test equality)

Simple reproducible example:

 const stocks = [ { id: 11, symbol: 'AAPL', name: 'Apple', category: 'Tech' }, { id: 12, symbol: 'AAPL', name: 'Orange', category: 'Fruit' }, { id: 13, symbol: 'AAPL', name: 'Not Apple', category: 'Fruit' }, ]; console.log(stocks.filter(xx => xx.category = 'Tech'));

In this case you're updating every element's category to 'Tech' (look at the result of first snippet, all categories are 'Tech' now), then you return 'Tech' to the filter function who's always 'true'

 console.log(foo = "bar"); // Assignment also return the value console.log(!!foo); // A non-null value is `true` (as boolean)

So you filter function will always test if (!!'Tech' === true) (always true ), so return every elements updated.

You just need to use the === to return the correct boolean

 const stocks = [ { id: 11, symbol: 'AAPL', name: 'Apple', category: 'Tech' }, { id: 12, symbol: 'AAPL', name: 'Orange', category: 'Fruit' }, { id: 13, symbol: 'AAPL', name: 'Not Apple', category: 'Fruit' }, ]; console.log(stocks.filter(xx => xx.category === 'Tech'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM