Ragu
Ragu

Reputation: 155

Use map function for array object and display in table in React

I have an array object that looks like this: Array Object

This is coming from parent component. I want to display these in a table with all the headings(key) in a single column and their values in other columns. It should look something like this:enter image description here

I am doing like this:

In my child component I am calling function like this for object coming from parent:

  renderYear() {
  if (this.props.total_calculation.length === 0) {
  return null
} else {
  const Year = this.props.total_calculation.map(
    ({ Year }) => Year
  )
  return Year.map(function (d, key) {

    return (
      <td key={key} colSpan="2">
        {(d)}
      </td>
    )

  })

  }
}

This is creating td for all the values of each key in the objects(in this function it is year).

And in its render I made a table and render all these tds like this:

    <table>
          <tbody>
            <tr className='year'>
              <td>Year</td>
              this.renderYear()
            </tr>

I know this is not a good coding way because for each key(like year, rent_increase,...) I have to make a separate function and then render it.

Can you please suggest some efficient way to do this? or if I can optimize the map function.

Upvotes: 0

Views: 1660

Answers (2)

Sarun UK
Sarun UK

Reputation: 6736

You can try the below code,

const renderField = () =>
          this.props.total_calculation.length > 0 ? (
          this.props.total_calculation.map(function (obj, key) {
            return (
                <td key={key} colSpan="2">
                    {obj['Year']}
                </td>
            );
        })) : null;

Upvotes: 0

Antenaina
Antenaina

Reputation: 164

Your problem might not be an optimization problem. What you are searching for is to have only one function that return the render for keys of your object. Here is a suggestion:

  • Change you renderYear() method to this:
    renderField(objectKey) {
        if (this.props.total_calculation.length === 0) {
            return null;
        }
        return this.props.total_calculation.map(function (obj, key) {
            return (
                <td key={key} colSpan="2">
                    {obj[objectKey]}
                </td>
            );
        });
    }

The argument objectKey of the renderField() method takes as argument a string that is a key of the object you want to render. Then now you can call it like this:

        <tr className='year'>
            <td>Year</td>
            {{this.renderField('Year')}}
        </tr>

You can call the renderField() method on other key of your object like 'rent_increase'
You should also check the Open/closed principle of the SOLID principles because your problem has similar solution to it.

Upvotes: 1

Related Questions