score:0

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;

score:1

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.


Related Query

More Query from same tag