Angular Pipe To Filter Text With Multi Level Key
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 { P
Solution 1:
try to use lodash
's get()
function:
import { Pipe, PipeTransform } from'@angular/core';
import * as lodash from'lodash';
@Pipe({ name: 'simpleSearch' })
exportclassSimpleSearchPipeimplementsPipeTransform {
publictransform(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 && newRegExp(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.
Solution 2:
Extract the nested object values based on this:
var myObj = {
key: 'myKcley',
fields: {
summary: 'asdf'
}
};
vargetNestedObject = (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);
}
});
Post a Comment for "Angular Pipe To Filter Text With Multi Level Key"