import {isNullOrUndefined} from 'util'; import {Pipe, PipeTransform} from '@angular/core'; import {NameValue} from '../types/name-value'; /** * @author Harsha A.N.S */ @Pipe({ name: 'filter' }) export class FilterParentPipe implements PipeTransform { transform(objects: any[], parentName: string, parentData: any, childName: string): any[] { // if parent is all then return all child elements if (typeof 'parentData' === 'string' && parentData.toString().toUpperCase() === 'ALL') { return this.getChildObject(objects, childName); } if (parentName === undefined || parentData === undefined || childName === undefined ) { return objects; } const filterObject = objects.filter(object => { return object[parentName] === parentData; }); const childObject: any[] = this.getChildObject(filterObject, childName); return childObject; } transformMulti(objects: any[], parentNames: string[], parentData: any[], childName: string): any[] { let childData: any[] = JSON.parse(JSON.stringify(objects)); const filteredChildData = parentNames.forEach((p, index) => { if ( !p || !parentData[index] || !childName || parentData[index].toUpperCase() === 'ALL') { return; } childData = childData.filter(x => { return x[p] === parentData[index]; }); }); childData = this.getChildObject(childData, childName); return childData; } getChildObject(filterObject: any, childName: string): any[] { const childObject: any[] = []; filterObject.forEach(x => { childObject.push(x[childName]); }); if (childObject[0] === null || childObject[0] === undefined) { return new Array(new NameValue('All', 'All')); } return this.removeDuplicates(childObject, 'name'); } private removeDuplicates(originalArray, prop) { const newArray = []; const lookupObject = {}; for (const i of Object.keys(originalArray)) { lookupObject[originalArray[i][prop]] = originalArray[i]; } for (const i of Object.keys(lookupObject)) { newArray.push(lookupObject[i]); } return newArray; } }