如何在Angular 2模板中对数据和输出进行分组 - 使用管道?

时间:2017-02-10 23:07:35

标签: angular group-by pipe ionic2

我是一个Angular 2项目,我正在获取一个结果列表,我希望在UI中显示为组。我想按照返回的值之一进行分组,并显示组中项目的详细信息。

目前,我已尝试使用this groupby pipe来完成此操作,但我无法在模板中使用它。

我试过了:

<ion-list>
    <div *ngFor="let item of searchresults | orderBy:'item[0]'">
        <ion-item-divider sticky>{{ item[2] }}</ion-item-divider>
        <ion-item (click)="itemTapped($event, item)">{{ item[0] }}</ion-item>
    </div>
</ion-list>

api返回:

{"results":[
["Chocolade vlokken melk pak 300 gram  ","8710400407010","Albert Heijn","Hagelslag",1,2,"","701",""],
["Chocolade vlokken puur pak 300 gram  ","8710400406990","Albert Heijn","Hagelslag",1,1,"","701",""],
["Chocoladevlokken melk pak 300 gram (Kiekeboe)  ","23029217","Aldi","Hagelslag",1,2,"","612",""],
["Chocoladevlokken puur pak 300 gram (Kiekeboe)  ","23029217","Aldi","Hagelslag",1,2,"","612",""],

] &#34; API_VERSION&#34;:0.2}

1 个答案:

答案 0 :(得分:4)

更新#2:
StackBlitz 上添加了示例,因为plunk上的引用是陈旧的(并且因为StackBlitz使用/管理更友好)。

更新#1:
我构建了一个 plunkr ,它使用一种更容易理解的方法将未分组的数据转换为分组对象数组以及使用它的示例。我还提供了一个如何动态更改分组值的演示。

原文答案:
我建议您在组件中进行分组,而不是作为管道进行分组,原因有多种,如explained here in the Angular documentation

下面是一些ES6代码,您可以使用它们将结果转换为分组结果,从而使您的显示非常简单。将其拖入页面,然后在控制台中查看分组结果。

<script>
    const myData = {
        "results": [
            ["Chocolade vlokken melk pak 300 gram  ", "8710400407010", "Albert Heijn", "Hagelslag", 1, 2, "", "701", ""],
            ["Chocolade vlokken puur pak 300 gram  ", "8710400406990", "Albert Heijn", "Hagelslag", 1, 1, "", "701", ""],
            ["Chocoladevlokken melk pak 300 gram (Kiekeboe)  ", "23029217", "Aldi", "Hagelslag", 1, 2, "", "612", ""],
            ["Chocoladevlokken puur pak 300 gram (Kiekeboe)  ", "23029217", "Aldi", "Hagelslag", 1, 2, "", "612", ""],
        ],
        "api_version": 0.2
    };

    // transform results into grouped results
    // you can easily extract this into a function and just pass your results in and the array index you want to group on
    const groupedResults = [...myData.results.reduce((hash, result) => {
        // specify the value from each of your 'results' that you want to group on
        group = result[2];
        // Add the result to existing group if it exists, or create a new group and add it
        const currentGroup = hash.get(group) || { group, items: [] };
        currentGroup.items.push(result);
        return hash.set(group, currentGroup);
    }, new Map).values()];

    // show grouped results in the console
    console.log("New Grouped Results: ", groupedResults);

</script>