myTest532 myTest532
myTest532 myTest532

Reputation: 2381

Get specific elements in array of objects

I'm trying to set my table data with some, not all, of data from my props array of objects.

I set an array of objects from my action:

export const getTenants = ({ userID }) => {
  return (dispatch) => {
    const test = [
      { id: 1, fullName: 'Tenant 1', unitName: '101', leaseEndDate: '01/01/2020', tenantEmail: '[email protected]' },
      { id: 2, fullName: 'Tenant 2', unitName: '102', leaseEndDate: '01/01/2020', tenantEmail: '[email protected]' },
      { id: 3, fullName: 'Tenant 3', unitName: '103', leaseEndDate: '01/01/2020', tenantEmail: '[email protected]' },
      { id: 4, fullName: 'Tenant 4', unitName: '104', leaseEndDate: '01/01/2020', tenantEmail: '[email protected]' },
      { id: 5, fullName: 'Tenant 5', unitName: '105', leaseEndDate: '01/01/2020', tenantEmail: '[email protected]' },
      { id: 6, fullName: 'Tenant 6', unitName: '106', leaseEndDate: '01/01/2020', tenantEmail: '[email protected]' },
      { id: 7, fullName: 'Tenant 7', unitName: '107', leaseEndDate: '01/01/2020', tenantEmail: '[email protected]' },
      { id: 8, fullName: 'Tenant 8', unitName: '108', leaseEndDate: '01/01/2020', tenantEmail: '[email protected]' },
    ];
    dispatch({
      type: GET_TENANT_DATA,
      payload: test
    });
  };
};

Then, in my page I want to set the tableData with the unit, lease end date, name, and email only and in this order.

this.state = {
          tableHead: ['Unit', 'Lease End Date', 'Tenant', 'Tenant Email'],
          tableData: this.props.data
        };

Is there a way to do it? Thanks

Upvotes: 0

Views: 47

Answers (1)

Zaytri
Zaytri

Reputation: 2574

Set a header => object key mapping and loop through tableHead to extract the data you need.

this.headerMap = {
  'ID': 'id',
  'Tenant': 'fullName',
  'Unit': 'unitName',
  'Lease End Date': 'leaseEndDate',
  'Tenant Email': 'tenantEmail',
}

this.state = {
  tableHead = ['Unit', 'Lease End Date', 'Tenant', 'Tenant Email'],
  tableData: this.props.data.map(row => tableHead.map(header => row[this.headerMap[header]]))
}

This creates an array of arrays:

[
  ['101', '01/01/2020', 'Tenant 1', '[email protected]'],
  ['102', '01/01/2020', 'Tenant 2', '[email protected]'],
  ['103', '01/01/2020', 'Tenant 3', '[email protected]'],
  ['104', '01/01/2020', 'Tenant 4', '[email protected]'],
  ['105', '01/01/2020', 'Tenant 5', '[email protected]'],
  ['106', '01/01/2020', 'Tenant 6', '[email protected]'],
  ['107', '01/01/2020', 'Tenant 7', '[email protected]'],
  ['108', '01/01/2020', 'Tenant 8', '[email protected]']
]

Upvotes: 1

Related Questions