angular pipe to filter text with multi level key

≯℡__Kan透↙ 提交于 2020-01-25 08:40:08

问题


I have an angular pipe which just filter outs the text from ngFor. It works very well with single level of json object but fails when there is multi level object.

Pipe:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({   name: 'simpleSearch' })
  export class SimpleSearchPipe implements PipeTransform {

  public transform(value, keys: string, term: string) {

    if (!term) return value;
    return (value || [])
        .filter(item => 
             keys.split(',').some(key => {
                item.hasOwnProperty(key) && new RegExp(term, 'gi').test(item[key])
             })
        );
   }
}

template:

<div *ngFor="let issue of issuesData
      | simpleSearch: 'key,fields.summary,fields.priority.name': searchTerm"
></div>

Here the search works very well for the field "key" (1st level of json object) but doesn't works for other keys.

Can anyone please help me fix this or please let me know if you need some more info.


回答1:


try to use lodash's get() function:

import { Pipe, PipeTransform } from '@angular/core';

import * as lodash from 'lodash';

@Pipe({ name: 'simpleSearch' })
export class SimpleSearchPipe implements PipeTransform {

  public transform(value, keys: string, term: string) {

    if (!term) return value;
    return (value || [])
      .filter(item =>
        keys.split(',').some(key => {
          const val = lodash.get(item, key, undefined);
          return val !== undefined && new RegExp(term, 'gi').test(val);
        })
      );
  }
}

also, in your some() function you need to return boolean by providing return statement or by removing curly brackets. I added return in your code.

STACKBLITZ




回答2:


Extract the nested object values based on this:

var myObj = {
    key: 'myKcley',
    fields: {
        summary: 'asdf'
    }
};

var getNestedObject = (nestedObj, pathArr) => {
    return pathArr.reduce((obj, key) =>
        (obj && obj[key] !== 'undefined') ? obj[key] : undefined, nestedObj);
}

var objKeys = 'key, fields.summary';
objKeys.split(',').forEach(key => {
    if(key.includes('.')) {
        var keyArray = key.trim().split('.');

        var value = getNestedObject(myObj, keyArray);
        console.log(value);

    }
});


来源:https://stackoverflow.com/questions/52692302/angular-pipe-to-filter-text-with-multi-level-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!