Как я могу отфильтровать объект объектов в угловых 7 трубы (элемент для объекта) - PullRequest
0 голосов
/ 08 ноября 2018

** Угловой 7 - ТРУБА **

Я провожу тест, в котором мне нужно отобразить таблицу, заполненную из JSON, которая содержит мета-объект (ы). в * ng для меня есть следующее:

 <tr>
    <th *ngFor="let one of meta | customData"  [ngClass]="one.value.visibility">
            {{ one.title }}
    </th>
 <tr>

В customData pipe у меня есть следующее:

    for (const [key1 , val1] of test) {
      for (const [key2 , val2] of  val1) {

        switch (key2) {
          case ('title'):
            Otitle = 'title';
            break;
          case (key2.toString() === 'data_type'):
            Otype = val2;
            break;
          case (key2.toString() === 'format'):
            Oformat = val2;
            break;
          default:
            break;
        }
       })
    })

Поскольку полученные данные являются объектами объектов, я подумал, что использую канал, который возвращает соответствующее желаемое значение. Канал получает объект и назначает «тест» соответствующему узлу. Затем я повторяю через значения «test» объекта, чтобы вернуть объект, который содержит «title», «data_type» и «format». Я надеялся, что смогу использовать канал повторного использования для доступа к требуемому значению.

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

@Pipe({
  name: 'customData'
})
export class CustomDataPipe implements PipeTransform {
  transform(value: any, args ? : any): any {
    /** Testing *****************************/
    console.log('%c customData PIPE in Value', 'color: Blue; font-weight:bold;');
    console.table(value);
    /** Testing *****************************/
    try {
      let test: any;
      test =
        value.hasOwnProperty('portfolio_attribute_elements') ? value.portfolio_attribute_elements : false;
      /** Testing *****************************/
      console.log('%c customData PIPE in test assigned value', 'color: Blue; font-weight:bold;');
      console.table(test);
      /** Testing *****************************/
      if (test !== false) {
        console.log('%c LOGIC (test !== false) evaluates to: ' + (test !== false), 'font-weight;bold;font-size:1.4em;');
        let Otitle = null;
        let Otype = null;
        let Oformat = null;

        for (const [key1, val1] of test) {
          for (const [key2, val2] of val1) {

            switch (key2) {
              case ('title'):
                Otitle = 'title';
                break;
              case (key2.toString() === 'data_type'):
                Otype = val2;
                break;
              case (key2.toString() === 'format'):
                Oformat = val2;
                break;
              default:
                break;
            }
          })
      })

    /** Testing *****************************/
    console.log('%c customData PIPE -> assumed end object', 'color: Blue; font-weight:bold;');
    console.table({
      title: Otitle,
      type: Otype,
      format: Oformat
    });
    /** Testing *****************************/
    return {
      title: Otitle,
      type: Otype,
      format: Oformat
    };
  }
  /** Testing *****************************/
  console.log('%c customData PIPE Failed IF Stateent', 'color: Blue; font-weight:bold;');
  console.table(value);
  /** Testing *****************************/
  return value;

} catch (error) {
  console.log('%c ERROR: -> ' + error.message, 'color: red; font-weight: bold;font-size:2em;');
  return value;
}
}
}

// the MetaData
{
  "components": {
    "table_filters": {
      "sections": [
        "section_portfolio_type"
      ]
    },
    "table_portfolio_attributes": {
      "sections": [
        "section_portfolio_attributes"
      ]
    }
  },
  "portfolio_attribute_elements": {
    "portfolio_attribute_asset_count": {
      "data_type": "number",
      "format": {
        "digits_info": "1.0-0"
      },
      "title": "# Bonds"
    },
    "portfolio_attribute_avg_rating": {
      "data_type": "string",
      "order": "specialOrder",
      "title": "Avg. Rating"
    },
    "portfolio_attribute_avg_yield": {
      "data_type": "mul100_percent",
      "format": {
        "digits_info": "1.1-2"
      },
      "title": "Avg. Yield"
    },
    "portfolio_attribute_creation_date": {
      "data_type": "date",
      "format": {
        "date_format": "yyyy-MMM-dd"
      },
      "title": "Date Created"
    },
    "portfolio_attribute_currency": {
      "data_type": "string",
      "title": "Currency"
    },
    "portfolio_attribute_current_capital": {
      "data_type": "number",
      "format": {
        "digits_info": "1.0-0"
      },
      "title": "Current Capital"
    },
    "portfolio_attribute_duration": {
      "data_type": "time_period",
      "format": {
        "digits_info": "1.0-2",
        "period": "Y"
      },
      "title": "Avg. Duration"
    },
    "portfolio_attribute_last_modified": {
      "data_type": "date",
      "format": {
        "date_format": "yyyy-MMM-dd"
      },
      "title": "Last Updated"
    },
    "portfolio_attribute_name": {
      "data_type": "string",
      "title": "Portfolio Name"
    },
    "portfolio_attribute_portfolio_id": {
      "data_type": "string",
      "title": "--Internal--",
      "visibility": "force-hidden"
    },
    "portfolio_attribute_type": {
      "data_type": "string",
      "title": "Portfolio Type"
    }
  },
  "sections": {
    "section_portfolio_attributes": {
      "portfolio_attribute_elements": [
        "portfolio_attribute_portfolio_id",
        "portfolio_attribute_type",
        "portfolio_attribute_name",
        "portfolio_attribute_currency",
        "portfolio_attribute_current_capital",
        "portfolio_attribute_asset_count",
        "portfolio_attribute_avg_yield",
        "portfolio_attribute_duration",
        "portfolio_attribute_avg_rating",
        "portfolio_attribute_creation_date",
        "portfolio_attribute_last_modified"
      ]
    },
    "section_portfolio_type": {
      "form_elements": [
        "portfolio_type"
      ]
    }
  }
}
<div class="container-fluid">
  <app-navbar></app-navbar>
  <table class="table table-bordered table-hover" id="portfolios">
    <thead>
      <tr>
        <th *ngFor="let one of meta | customData" [ngClass]="one.value.visibility">
          {{ one.title }}
        </th>
        <tr>
    </thead>
    <!--tbody>
              <tr *ngFor="let item of portfolios.portfolios.items | keyvalue | slice: 1:100">
                <td *ngFor="let one of item.value | keyvalue | reverse | slice: 0:11" >
                  {{ one.value.value }}
                </td>
              </tr>
          </tbody-->
  </table>
</div>

Любая помощь будет высоко ценится :) Заранее спасибо

...