0

I am getting array in props which is props.logsInfo.logs and I want to use it according to the number of elements in array instead of hard coding it like props.logsInfo.logs[0]['id']. I want to use map.Logs array size can be more than one.I don't want to write one more cells: [ { key: 'cell-0', children: props.logsInfo.logs[1]['id'] },How can i achieve it??

import React from 'react';
import Table from 'terra-table';
const StripedTable = props => (
  <Table
    summaryId="striped-table"
    summary="This table displays striped rows."
    numberOfColumns={4}
    dividerStyle="horizontal"
    headerData={{
      cells: [
        { id: 'header-Id', key: 'id', children: 'Id' },
        { id: 'header-vendorId', key: 'vendorId', children: 'VendorId' },
        { id: 'header-userId', key: 'userId', children: 'UserId' },
        { id: 'header-payLoad', key: 'payLoad', children: 'PayLoad' },
      ],
    }}

    bodyData={[
      {
        rows: [
          {
            key: 'row-0',
            cells: [
              { key: 'cell-0', children: props.logsInfo.logs[0]['id'] },
              { key: 'cell-1', children: props.logsInfo.logs[0]['vendorId'] },
              { key: 'cell-2', children: props.logsInfo.logs[0]['userId'] },
              { key: 'cell-3', children: props.logsInfo.logs[0]['payLoad']},
            ],
          },
        ],
      },
    ]}
  />
);
export default StripedTable;
3
  • Is this Table component used from some library Commented Mar 27, 2020 at 12:58
  • Will the props.logsInfo.logs can have only one element? You're only considering the first element in the question. Commented Mar 27, 2020 at 13:01
  • Tht is what it can have more than one element Commented Mar 27, 2020 at 13:16

1 Answer 1

1

Yes, you can use .map:

 bodyData={[
      {
        rows: props.logsInfo.logs.map(log => ({
          key: log.id,
          cells: [
            { key: 'cell-0', children: log.id },
            { key: 'cell-1', children: log.vendorId },
            { key: 'cell-2', children: log.userId },
            { key: 'cell-3', children: log.payLoad},
          ],
        }),
      },
    ]}

You can also do the same for cells if you keep an array with the field names around:

const fields = ['id', 'vendorId', 'userId', 'payLoad'];

// ...


 bodyData={[
      {
        rows: props.logsInfo.logs.map(log => ({
          key: log.id,
          cells: fields.map(field => ({key: field, children: log[field]})),
        }),
      },
    ]}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.