Фильтр поиска в элементе таблицы html [массив таблиц неоднороден] - PullRequest
1 голос
/ 06 января 2020

Я хочу поместить функцию фильтра в таблицу, где данные таблицы представляют собой неоднородный массив, как показано ниже:

let items [
        {
          "_resource":{
                   "values":[null, undefined, true, 'foobar', {'amount': 1111, 'isValid': true} , 1]// this table row, and each array's item represent individual column
             },
....
        },
        {
          "_resource":{
                   "values":[null, undefined, true, 'search in me', {'amount': 1111, 'isValid': true} , 1]// this table row, and each array's item represent individual column
             }
        }
....
]

Я добавил код фильтра, как показано ниже:

function filterItesm(items, text) {
      if (text.length == 0) {
        return items;
      }
      var temp = items;
      items = [];
      for (var i = 0; i < temp.length; i++) {

        var item = items[i];
        var values = item._resource.values;
        var found = false;

        for (var j = 0; j < values.length; j++) {
           var currItem = values[j];
          if (typeof currItem === 'object') {
            for (var name in currItem) {
              if (currItem[name] != null) {
                if(typeof currItem[name] == 'number') {
                  if(text.toLowerCase().indexOf(currItem) > -1) {
                    found = true;
                    break;
                  }
                } else {
                  if (""+currItem.toLowerCase().indexOf(text.toLowerCase()) > -1) {
                    found = true;
                    break;
                  }
                }
              }
            }
          } else if(typeof currItem == 'number'){
            if(text.toLowerCase().indexOf(currItem) > -1) {
              found = true;
            }
          } else if(typeof currItem == 'string') {
            if (currItem.toLowerCase().indexOf(text.toLowerCase()) > -1) {
              found = true;
            }
          }
        }
        if (found == true) {
          items.push(item);
          found = false;
        }
      }
       return items;
    }

Здесь фильтр работает, но я ищу лучший подход. Любая помощь будет заметна.

1 Ответ

0 голосов
/ 06 января 2020

Если вы используете Angular, то вы можете сделать это следующим образом.

На странице компонента. html вы можете внести следующие изменения в таблицу html.

<div class="search-hero">
                  <input class="form-control" type="text" name="search" [(ngModel)]="searchText" autocomplete="off" placeholder="Search">
              </div>

               <table class="table table-bordered" width="100%" cellspacing="0">
                <thead>
                  <tr>
                    <th>Thumbnail</th>
                    <th>Book Name</th>
                    <th>Author</th>
                    <th>Price</th>
                    <th> Edit</th>
                    <th> View</th>
                  </tr>
                </thead>

                <tbody>
                    <tr *ngFor ="let b of books | filter:searchText"> 
                        <td>  <img style="width: 5rem; height: 5rem;" src={{b.ThumbnailUrl}}></td>
                        <td>{{b.BookName}}</td>
                        <td>{{b.AuthorName}}</td>
                        <td>{{b.Price}}</td>
                        <td><button  class ="btn btn-primary"  (click)=editBookDetails(b)>Edit</button></td>  
                        <td><button  class ="btn btn-success"  (click)=viewBookDetails(b)>View</button></td>  
                    </tr>
                </tbody>


              </table>

В файле component.ts вы выполняете следующие действия:

searchText: String;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...