我有一个JSON对象,我需要对其进行迭代并包括一个搜索功能,该功能可显示键和在该键中搜索到的值。
我通过使用管道并通过遍历键及其值来实现这一点。
COMPONENT.HTML:
SapHealth
COMPONENT.TS:
<input type="text" class="form-control" placeholder = "Search"[(ngModel)] = "query" id = "listSearch" #search >
<ul>
<li * ngFor="let key of objectKey()" >
<span>{{ key }}</span>
< table >
<tr * ngFor="let item of (testData[key] | LockFilter:'appName': search.value) as result" >
<td>{{ item.appName }}</td>
< /tr>
< /table>
< /li>
< /ul>
PIPE.TS:
testData = {
"MyCat1": [
{
"appName": "Myapp1",
"appCatName": "MyCat1"
},
{
"appName": "Myapp2",
"appCatName": "MyCat1"
}
],
"MyCat2": [
{
"appName": "Myapp3",
"appCatName": "MyCat2"
},
{
"appName": "Myapp4",
"appCatName": "MyCat2"
}
]
}
objectKey() {
return Object.keys(this.testData);
}
搜索前的预期结果: MyCat1: Myapp1 Myapp2
MyCat2: Myapp3 Myapp4
搜索后:(搜索字符串“ 1”) MyCat1: Myapp1
答案 0 :(得分:0)
尝试一下:
<input [(ngModel)]="search" />
<ul>
<li *ngFor="let key of objectKey()" [hidden]="!(testData[key] | LockFilter:'appName': search).length">
<span>{{ key }}</span>
<table>
<tr *ngFor="let item of (testData[key] | LockFilter:'appName': search) as result">
<td> {{ item.appName }}</td>
</tr>
</table>
</li>
</ul>
答案 1 :(得分:0)
尝试一下
// check if exists and will return the keys
objectKey(value) {
return Object.entries(this.testData)
.filter(data=> (data[1].filter(item=> item[value].includes(this.search)).length))
.map([KEY, VAL] => KEY)
}
HTML(相同代码)
<ul>
<li *ngFor="let key of objectKey('appName')" >
<span >{{ key }}</span>
<table>
<tr *ngFor="let item of (testData[key] | LockFilter:'appName': search) as result" >
<td > {{ item.appName }}</td>
</tr>
</table>
</li>
</ul>