Попытка l oop над объектом, используя Момент JS - PullRequest
0 голосов
/ 28 февраля 2020

У меня есть раздел, который извлекает данные из массива, отображает их и группирует по месяцам. Чтобы показать объект даты, мне нужно удалить слой из файла JSON.

Такое ощущение, что я что-то упустил что-то очень маленькое, и мне просто нужно внести небольшое изменение в l oop по массиву данных. Кто-нибудь может указать, что я делаю неправильно?

Вот таблица, которая отображает данные:

<table class="table" *ngFor="let month of transactions | keyvalue">
    <tr>
        <th>{{month.key}}</th>
    </tr>
    <tr>
        <td>
            <table class="table" *ngFor="let customer of month.value">
                <tr>
                    <td>
                        {{customer}}
                    </td>
                </tr>
            </table>
        </td>
    </tr>
</table>

Это компонент, который группирует данные:

export class AppComponent {

  public transactions = {};
  // Sample Data
  customers = [
    {
      data: [
        {
          customer: {
            name: "John"
          },
          // transaction_date: "2017-04-18"
          transaction_date: "2019-9-22T13:56:11.971643+00:00"
        },
        {
          customer: {
            name: "Dick"
          },
          transaction_date: "2019-10-22T13:56:11.971643+00:00"
        },
        {
          customer: {
            name: "Harry"
          },
          transaction_date: "2019-7-22T13:56:11.971643+00:00"
        },
        {
          customer: {
            name: "John"
          },
          transaction_date: "2019-9-22T13:56:11.971643+00:00"
        }
      ]
    }
  ];

  constructor() {}

  ngOnInit() {
    const monthName = item =>
      moment(item.transaction_date, "YYYY-MM-DD").format("MMM");

    // Establish groupBy array
    this.transactions = _.chain(this.customers)
      .groupBy(monthName)
      .mapValues(items => _.map(items, "customer.name"))
      .value();

    const byMonth = _.chain(this.customers)
      .groupBy(monthName)
      .mapValues(items => _.map(items, "customer.name"))
      .value();
    console.log(byMonth);
    return byMonth;
    console.log(this.customers2);
  }
}

Если я отформатирую Json иначе, он будет работать, но мне нужно, чтобы он работал и с массивом data [].

// Working Array
  customers2 = [
    {
      customer: {
        name: "John"
      },
      // transaction_date: "2017-04-18"
      transaction_date: "2019-9-22T13:56:11.971643+00:00"
    },
    {
      customer: {
        name: "Dick"
      },
      transaction_date: "2019-10-22T13:56:11.971643+00:00"
    },
    {
      customer: {
        name: "Harry"
      },
      transaction_date: "2019-7-22T13:56:11.971643+00:00"
    },
    {
      customer: {
        name: "John"
      },
      transaction_date: "2019-9-22T13:56:11.971643+00:00"
    }
  ];

1 Ответ

1 голос
/ 28 февраля 2020

Попробуйте:

 this.transactions = _.chain(this.customers[0].data)

 const byMonth = _.chain(this.customers[0].data)

Рабочая stackblitz .

UPDATE

Ваша customers переменная-член массив только с одним элементом.

Это было причиной добавления [0] для доступа к нему.

Вы просто получаете доступ к первому элементу в массиве, как этот. Имя массива и значение индекса (на основе нуля).

Еще несколько примеров:

customers = []; // <-- simple array

customers = [{}]; // <-- simple array with one object in it

Как получить к нему доступ?

customers[0] // <-- first element

Ваш случай:

customers = [{ data: [] }]; // <-- simple array with one object in it with a property "data" which is another array.

Как получить к нему доступ?

customers[0].data // <-- the solution

...