我有一个对象数组。我的对象有一个“类别”属性。我想过滤对象数组以仅返回具有“技术”类别的对象。
抛出的错误是类型 {} 上不存在“filter”
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');
}
}
最佳答案
您只需将 xx.category = 'Tech'
(谁更新)替换为 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
),因此返回每个更新的元素。
您只需要使用===
即可返回正确的 bool 值
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'));
关于javascript - typescript /Angular : Filter array of objects,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59273779/