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');
}
}
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');
}
}
Share
Improve this question
edited Dec 10, 2019 at 19:07
user1698144
asked Dec 10, 2019 at 19:02
user1698144user1698144
7644 gold badges14 silver badges37 bronze badges
1
-
You should be using a strict parison.
xx.category === 'Tech'
– Christopher Marshall Commented Dec 10, 2019 at 19:05
1 Answer
Reset to default 6You 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'));