Search code examples
javascriptangularpipefor-in-loopnest-nested-object

*ngFor Angular through nested array with different keys and level


I have an array of objects with an "asymetric" structure where keys are not the same and there are some nested object. I need loop through this:

  obj = [{
      "d14042018": {
        "date": "14-04-2018",
        "value": 5
      },
      "d02042018": {
        "date": "02-04-2018",
        "value": 10
      },
      "name": "my name"
    },
    {
      "d14042018": {
        "date": "14-04-2018",
        "value": 15
      },
      "d02042018": {
        "date": "02-04-2018",
        "value": 25
      },
      "name": "my second name"
    }]

what i need is to return a structure like this

first row = my name 5 10

second row = my second name 15 25

I tried a for in a custom Pipe...

    import { Pipe, PipeTransform } from '@angular/core';
    @Pipe({
      name: 'keys'
    })
    export class KeysPipe implements PipeTransform {

      transform(value: any, args?: any): any {
        let keys: string;

        if (value) {
          for (var prop in value) {
      
            if(typeof value[prop] != 'object') {
               keys = value[prop];
            } else {
              for (var subprop in prop) {
                keys = prop.subprop;
              }
            }
          }
        }
        return keys;
      }
    }

but id doesn't work...

can someone help?


Solution

  • I'd recommend avoid using a Pipe for this type of advanced data manipulation and instead just generate the necessary data structure for display/usage in something like ngOnInit() or prior to binding to a public variable. You can use Object.keys() in combination with Array.prototype.map(), Array.prototype.join() and ternary statements to generate the data rows.

    TypeScript:

    this.rows = Object.keys(obj).map(key => {
      const o = this.data[key];
      const { name } = o;
      const values = Object.keys(o)
                       .map(k => o[k]['value'])
                       .join(' ');
    
      return { name, values };
    });
    

    HTML:

    <ul>
      <li *ngFor="let row of rows">{{row.name}} {{row.values}}</li>
    </ul>
    

    Here is an example in action.

    Hopefully that helps!