在Angular 2中使用ng时,如何在数组通过管道后获取对象内的原始索引?
例如,如果我有一个对象数组,如下所示:
list = [{type:"A",id:111},{type:"A",id:222},{type:"B",id:333},{type:"A",id:444},{type:"B",id:555}];
Run Code Online (Sandbox Code Playgroud)
并使用以下管道:
@Pipe({
name: 'appFilter',
pure: false
})
export class AppFilterPipe implements PipeTransform {
// Single Argument Filter
transform(values: any[], arg1: any, arg2: any): any {
return values.filter(value => value[arg1] === arg2);
}
}
Run Code Online (Sandbox Code Playgroud)
我创建一个ngFor如下:
<div *ngFor= "let item of list|AppFilter:'type':'B'|let index=index;trackBy:trackByIndex;">
{{index}} - {{item.id}}
<input [(ngModel)]="list[index]" placeholder="item">
</div>
Run Code Online (Sandbox Code Playgroud)
这里的问题是ngFor返回的索引是基于AppFilter返回的索引为0和1的新数组.这将导致输入字段引用错误的索引,即它将显示类型A对象,因为它对应于索引0 ,1在原始列表中.要获得Type BI,确实需要索引2,4.
欣赏这方面的工作.我的组件中的trackByIndex目前看起来像:
trackByIndex(index: number, obj: any): any {
return index;
}
Run Code Online (Sandbox Code Playgroud) 在Ionic的旧版本1中,我能够构建按日期分组的事件列表,如下所示:
<ion-list ng-repeat="(key, value) in events| groupBy: 'event.date'">
<div class="item item-divider" ng-if="value">
{{ ::key | event.date }}
</div>
<ion-item class="item" ng-repeat="event in value track by event.event.event_id">
{{ ::event.event.title }}
</ionic-item>
</ion-list>
Run Code Online (Sandbox Code Playgroud)
虽然事件对象看起来像这样(事件#1和#3共享相同的日期):
{
"events": [
{
"id": 1,
"date": "2017-12-26",
"title": "First event"
},
{
"id": 2,
"date": "2017-12-30",
"title": "Second event"
},
{
"id": 3,
"date": "2017-12-26",
"title": "Third event"
},
{
"id": 4,
"date": "2017-12-31",
"title": "Last event"
}
]
}
Run Code Online (Sandbox Code Playgroud)
这给了我一个存储在"事件"对象中的事件列表,这些事件按"event.date"分组.所以在同一天的所有事件都按项目分隔符分组:
+--------------+
+ 2017-12-26 +
+--------------+
| …Run Code Online (Sandbox Code Playgroud) 我有一个带有对象的 JSON 数据库。每个属性都有一个特定的赋值:a、b 或 c。
[
{
"id": 1,
"category": "a"
},
{
"id": 2,
"category": "b"
},
{
"id": 3,
"category": "c"
},
{
"id": 4,
"category": "a"
},
{
"id": 5,
"category": "a"
},
{
"id": 5,
"category": "b"
}
]
Run Code Online (Sandbox Code Playgroud)
我想显示如下内容:
共有6 个项目: ax 3、 bx 2和 cx 1。
我知道我必须使用objectsinmyjsondatabase.length才能获得总数。
我想知道如何获得具有特定值的对象的长度(数量)?