VadimDez / ngx-order-pipe

▼ Angular 5+ orderBy pipe
https://vadimdez.github.io/ngx-order-pipe/
MIT License
243 stars 57 forks source link

does not support deep properties #10

Closed esteban-url closed 7 years ago

esteban-url commented 7 years ago

it will not work on complex objects such as

var testObj = {
  a: 'b',
  'hyph"en': 10,
  "hy[ph]en": 11,
  b: {
    c: [1, 2, 3],
    d: ['h', 'ch'],
    e: [{}, {f: 'g'}],
    f: 'i'
  }
};

expressions such as 'b.c[0]' or b.e[2].f would fail

I've tried to add tests and run them on my fork but couldn't get it to work, or spend more time on it. so i fixed it on my project by adding lodash, this is what my pipe looks like now:

import { Pipe, PipeTransform } from '@angular/core';
import * as lodash from 'lodash';
declare var _: any;
_ = lodash;

@Pipe({
  name: 'orderBy'
})
export class OrderPipe implements PipeTransform {

    transform(value: any[], prop?: any, reverse?: boolean, option?: string): any {

      if (!value) {
        return value;
      }

      let array: any[] = value.sort((a: any, b: any): number => {
        let aa = _.get(a, prop);
        let bb = _.get(b, prop);
        if (option && option.localeCompare('case-insensitive')==0 &&
            this.isString(aa) && this.isString(bb)) {
          return aa.localeCompare(bb);
        }
        return aa > bb ? 1 : -1;
      });

      if (reverse) {
        return array.reverse();
      }

      return array;
    }

    isString(value: any) {
      return typeof value === 'string' || value instanceof String;
    }
  }