我正在为以下结构构建自定义过滤器管道
[
{
"client": {
"name": "DJASLDJSAKL"
},
"job_status": {
"name": "Scheduled"
},
"descriptor": "Lorem ipsum dolor sit amet consectetur adipiscing elit lacinia quam, ultrices leo interdum senectus integer ultricies venenatis nisl libero, et tellus nec litora volutpat proin duis neque. \r\n\r\nUt metus ac enim mauris malesuada bibendum lectus tincidunt nascetur phasellus, tristique quam libero purus dapibus nisl ultricies urna. \r\n\r\nNisl cubilia donec imperdiet nisi tempus venenatis cras egestas, duis senectus at orci ad porttitor in, magnis suspendisse sem ullamcorper neque tincidunt etiam.\r\n\r\nLitora pulvinar viverra et velit felis massa commodo etiam la.\r\n",
"duracion": {
"text": "00:00:00"
},
"tech": {
"eta_promise_date": "Nov 20 2019 03:05:00:PM"
},
"siteAddress": "537 West Thomas Drive Rolling Meadows, IL 60008"
}
]
我首先创建了一个仅在第一级或顶层起作用的函数。搜索我有一个主意,但与此同时我有点迷茫,这是我工作的方法
findObject(obj, searchTerm){
Object.keys(obj).forEach((key) => {
//let r = RegExp(searchTerm, 'gi').test(obj[key]);
if(obj === searchTerm){
console.log(`key: ${key}, value: ${obj[key]}`);
if(typeof obj[key] === 'object'){
this.findObject(obj[key], searchTerm);
}
return null;
}return null;
});
}
但是我此刻陷入无限循环
EDIT (添加视图部分)
<ion-list *ngFor="let order of workOrders | filtro: searchTerm">
<ion-item *ngFor = "let location of order.site" (click)="showOrderLocation(order)">
<ion-icon name="pin" item-start [ngStyle]="{'color':order.job_status.color}"></ion-icon>
<h4>{{order.code}}</h4><br>
<p>{{order.job_status.name}}</p><br>
<small>ETA: {{order.etaPromise}}</small><br>
<small>Deadline: {{this.relativeDate(this.utcToLocalTime(order.tech.eta_promise_date))}}</small><br>
<p>{{order.descriptor}}</p>
</ion-item>
</ion-list>
答案 0 :(得分:2)
您的递归函数有点混乱。根据对象的属性是否与findObject
匹配,boolean
函数应返回searchTerm
。
使用Object.keys(obj).forEach
遍历值是一个坏主意,因为它可以防止您中断递归,因此请使用简单的for循环。在您的情况下,您想打破递归的两种情况:字符串属性包含searchTerm
还是嵌套对象与searchTerm
匹配。
findObject(obj, searchTerm){
let pattern = new RegExp(searchTerm, 'gi');
const values = Object.values(obj)
for (let value of values) {
if (typeof value === 'string') {
// if value i a string, check if it matches!
if (pattern.test(value)) {
// match!
return true
}
} else if (typeof value === 'object') {
// use recursion to check if nested object contains the search term
const isMatch = this.findObject(value, searchTerm);
if (isMatch) {
return true
}
}
}
// no match, so return false
return false
}
答案 1 :(得分:1)
我将逻辑分为以下两个单独的方法:
const data = [
{...},
{...},
{...}
]
findObject(data: Array, searchTerm: string): Object {
for (let obj of data) {
if (this.contains(obj, searchTerm)) {
return obj;
}
}
return null;
}
contains(obj: Object, searchTerm: string): boolean {
for (let value of Object.values(obj)) {
if (typeof value === 'object') {
if (contains(value, searchTerm)) {
return true;
}
} else if (value.includes(searchTerm)) {
return true;
}
}
return false;
}