[英]Typescript/Angular: Filter array of objects
我有一个对象数组。我的对象有一个“类别”属性。 我想过滤对象数组以仅返回具有“技术”类别的对象。
抛出的错误是类型 {} 上不存在“过滤器”
股票列表.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');
}
}
您只需要将xx.category = 'Tech'
(who update) 替换为xx.category === 'Tech'
(谁测试相等性)
简单的可重现示例:
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'));
在这种情况下,您将每个元素的类别更新为“Tech”(查看第一个片段的结果,现在所有类别都是“Tech”),然后将“Tech”返回给始终为“true”的过滤器函数
console.log(foo = "bar"); // Assignment also return the value console.log(!!foo); // A non-null value is `true` (as boolean)
因此,您的过滤器函数将始终测试if (!!'Tech' === true)
(始终为true
),因此返回更新的每个元素。
您只需要使用===
返回正确的布尔值
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'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.