user1698144
user1698144

Reputation: 764

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');
  }
}

Upvotes: 0

Views: 9087

Answers (1)

Arthur
Arthur

Reputation: 5148

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'));

Upvotes: 6

Related Questions