2015-09-21 36 views
3

创建分频器如果我有一个JSON数组,看起来liket他下面..在奥里利亚

{ 
"error":false, 
"events":[ 
    { 
    "id":1, 
    "title":"First entry", 
    "date":"2014-11-04" 
    }, 
    { 
    "id":2, 
    "title":"Second entry", 
    "date":"2014-11-04" 
    }, 
    { 
    "id":3, 
    "title":"Third entry", 
    "date":"2014-11-05" 
    }, 
    { 
    "id":4, 
    "title":"Fourth entry", 
    "date":"2014-11-06" 
    }, 
    { 
    "id":5, 
    "title":"Fifth entry", 
    "date":"2014-11-06" 
    } 
] 
} 

如何在重复创建日期分隔,使得DOM看起来像这样..

2014 -11-04
首次进入
第二个条目

2014年11月5日
第三项

2014年11月6日
第四个条目
的第五项

+0

你只是想分组数据? –

+0

是的,没有。我想分组,这是我用分类功能完成的。但我也想显示它按照什么分组。每个标题都应该让用户知道该条目在哪个组中。 –

回答

3

我只想组阵列中的数据。

@bindable events = []; 
groupedEvents = []; 

eventsChanged(newValue) { 
    let matchedGroup; 
    // clear the array 
    this.groupedEvents = this.groupedEvents.splice(0, this.groupedEvents.length) 
    newValue.forEach(event => { 
    let match = this.groupedEvents.filter(group => { 
     return group.name === event.date; 
    })[0]; 
    if (!match) { 
     matchedGroup = { name: event.date, events: [] }; 
     this.groupedEvents.push(matchedGroup);  
    } 
    matchedGroup.events.push(event); 
    }); 
} 

,并在你的看法,你可以遍历组 -

<template repeat.for="group of groupedEvents"> 
    <h1>${group.name}</h1> 
    <ul> 
    <li repeat.for="event of group.events">${title}</li> 
    </ul> 
</template> 

JavaScript的分组主要是普通老式ES6 +代码,并很可能会有点更有效,但它应该给你一个开始。

+0

Brilliant&Elegant :) –

+0

为什么使用splice来清除数组? (我有几个问题,我不知道我完全理解那里发生了什么) 我还必须在forEach循环之外放置'let matchedGroup',否则每个事件都会被清除,事件不会添加到该matchedGroup数组。 –

+0

我不认为你想重新分配数组的值,如果你可以帮助它,这样你就不会破坏任何观察者。你是对的,匹配组需要在循环之外定义(我从未真正测试过代码:)) –