简体   繁体   English

数组中嵌套对象的角递归函数

[英]Angular recursive function for nested objects in array

I am building a custom filter pipe for the following structure我正在为以下结构构建自定义过滤器管道

[
    {
        "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"
    }
]

I first made a function that works only at first level, or top level.我首先创建了一个仅在第一级或顶级工作的函数。 Searching I have like an idea, but at the same time I'm kind of lost, this is the method in which I'm working搜索我有一个想法,但同时我有点迷茫,这就是我工作的方法

  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;

   });
  }

But I'm getting an infinite loop at the moment但我现在陷入无限循环

EDIT Adding the view section编辑添加视图部分

    <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>

Your recursion function is a little messy.你的递归函数有点乱。 The findObject function should return a boolean depending on whether or not a property of the object matches the searchTerm . findObject函数应该返回一个boolean具体取决于对象的属性是否与searchTerm匹配。

It's a bad idea to use Object.keys(obj).forEach to iterate over the values because it prevents you from breaking out of the recursion, so use a simple for loop instead.使用Object.keys(obj).forEach迭代这些值是一个坏主意,因为它会阻止您突破递归,因此请改用简单的 for 循环。 In your case there are two cases in which you want to break out of the recursion: if the string property contains the searchTerm or if a nested object matches the searchTerm .在您的情况下,有两种情况您想要中断递归:如果 string 属性包含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
}

I woulds split the logic into two separate methods as follows:我会将逻辑拆分为两个单独的方法,如下所示:

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 嵌套数组对象的递归函数返回未定义 - recursive function for nested array objects returns undefined 数组中嵌套对象的JavaScript递归函数 - JavaScript recursive function for nested objects in array Angular pipe 用于嵌套 arrays 和对象 | 递归 pipe - Angular pipe for nested arrays and objects | Recursive pipe 嵌套数组递归 map function - Recursive map function for nested array 修复:JS 递归 function 以获取嵌套(多级)子对象作为对象数组 - Fix: JS recursive function to get the nested (multilevel) child objects as array of objects 使用嵌套对象Angular 5过滤数组 - Filter array with nested objects Angular 5 递归 function 将 object 添加到深度嵌套的对象数组中,添加到错误的 object - Recursive function to add object into deeply nested array of objects adding into wrong object 递归 function 循环一个 object 并设置值,用嵌套属性数组连接对象 - Recursive function to loop an object and set value, with an array of nested properties to join objects 通过嵌套的对象数组递归循环来编写嵌套列表 - Recursive loop through nested array of objects to write nested list 递归函数和Map用于访问嵌套数组中的元素 - Recursive function and Map for accessing Elements in nested Array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM