打字稿/角度:过滤对象数组

时间:2019-12-10 19:02:55

标签: javascript angular typescript

我有一个对象数组。我的对象具有“类别”属性。我想过滤对象数组以仅返回“技术”类别”的对象。

类型为{}的错误不存在“过滤器”

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

1 个答案:

答案 0 :(得分:5)

您只需要用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'));

在这种情况下,您要将每个元素的类别更新为“技术”(看看第一个片段的结果,所有类别现在都是“技术”),然后将“技术”返回到始终为“真”的过滤器函数

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