Angular 2中的过滤器参数

时间:2018-08-01 20:59:40

标签: angular

我需要解释一下下面的Angular代码中的过滤器参数是什么,即x,idx和xs是什么。下面的 distinct 函数获取产品列表并返回不同类别的列表。我的问题是了解过滤器参数,即 x idx xs

const distinct = data => data
  .map(x => x.Category)
  .filter((x, idx, xs) => xs.findIndex(y => y.CategoryName === x.CategoryName) === idx);

distinct 方法获得如下列表:

[
{
    "ProductID": 1,
    "ProductName": "Chai",
    "SupplierID": 1,
    "CategoryID": 1,
    "QuantityPerUnit": "10 boxes x 20 bags",
    "UnitPrice": 18,
    "UnitsInStock": 39,
    "UnitsOnOrder": 0,
    "ReorderLevel": 10,
    "Discontinued": false,
    "Category": {
        "CategoryID": 1,
        "CategoryName": "Beverages",
        "Description": "Soft drinks, coffees, teas, beers, and ales"
    },
    "FirstOrderedOn": new Date(1996, 8, 20)
},
{
    "ProductID": 2,
    "ProductName": "Chang",
    "SupplierID": 1,
    "CategoryID": 1,
    "QuantityPerUnit": "24 - 12 oz bottles",
    "UnitPrice": 19,
    "UnitsInStock": 17,
    "UnitsOnOrder": 40,
    "ReorderLevel": 25,
    "Discontinued": false,
    "Category": {
        "CategoryID": 1,
        "CategoryName": "Beverages",
        "Description": "Soft drinks, coffees, teas, beers, and ales"
    },
    "FirstOrderedOn": new Date(1996, 7, 12)
},
{
    "ProductID": 3,
    "ProductName": "Aniseed Syrup",
    "SupplierID": 1,
    "CategoryID": 2,
    "QuantityPerUnit": "12 - 550 ml bottles",
    "UnitPrice": 10,
    "UnitsInStock": 13,
    "UnitsOnOrder": 70,
    "ReorderLevel": 25,
    "Discontinued": false,
    "Category": {
        "CategoryID": 2,
        "CategoryName": "Condiments",
        "Description": "Sweet and savory sauces, relishes, spreads, and seasonings"
    },
    "FirstOrderedOn": new Date(1996, 8, 26)
},
{
    "ProductID": 4,
    "ProductName": "Chef Anton's Cajun Seasoning",
    "SupplierID": 2,
    "CategoryID": 2,
    "QuantityPerUnit": "48 - 6 oz jars",
    "UnitPrice": 22,
    "UnitsInStock": 53,
    "UnitsOnOrder": 0,
    "ReorderLevel": 0,
    "Discontinued": false,
    "Category": {
        "CategoryID": 2,
        "CategoryName": "Condiments",
        "Description": "Sweet and savory sauces, relishes, spreads, and seasonings"
    },
    "FirstOrderedOn": new Date(1996, 9, 19)
}
]

2 个答案:

答案 0 :(得分:1)

实际上,您可以查看过滤器的类型:

filter(callbackfn: (value: T, index: number, array: T[]) => any, thisArg?: any): T[];

因此,首先获得一个类别列表,过滤器函数中的值为:

value = category element
index = index of the element
array = Category list (the one you get from the map)

答案 1 :(得分:0)

x是对象本身的值
idx是当前项目数组的索引[idx]
xs是数组映射