Dženis H.
Dženis H.

Reputation: 7822

Map over two arrays and display data in a single table?

Let's say I have two state properties in form of an array, like this:

constructor(props) {
    super(props);
    this.state = {
            fullNames: [],
            salaryInfo: []
        }}

...etc (a lot of other code where I receive props, make ajax requests)

What I'm trying to accomplish is to loop over these 2 arrays that I have in my state and display them inside of a one table.

For example, it's easy to do something like this:

const employeesFormated = fullNames
        .map(item => {
        return (
        <tr>
            <td>{item}</td>
        </tr>

const salariesFormated = salaryInfo
        .map(item => {
        return (
        <tr>
            <td>{item}</td>
        </tr>

... and then displayed it inside of a JSX table body:

                   <table>
                       <thead>
                        <tr>
                            <th>Employee name</th>                        
                        </tr>
                        </thead>
                        <tbody>
                            {employeesFormated}
                        </tbody>
                    </table>

... and the same could be done for the salaries array/ table. And with some additional CSS tricks maybe make it all work with two different tables placed in right places, but I was wondering if it's possible to map over the both and render them in a single table with corresponding data, meaning =>

Employee A === Salary A

Upvotes: 0

Views: 4095

Answers (1)

Abid Hasan
Abid Hasan

Reputation: 658

It might be easier if the state was an array of objects, with salary and name as keys, but if you know both fullNames and salaries are the same length and the indices correspond from one to the other (meaning salary at index i corresponds to name at index i), you could access them by index I guess.

const employeeTable = this.fullNames
        .map((item, idx) => {
        return (
        <tr>
            <td>{item}</td>
            <td>{this.state.salaryInfo[idx]}</td>
        </tr>
        )
        })  

Also, when you are rendering from arrays, React expects you to have a unique key prop to ensure DOM elements can be tracked. It will insert it for you based on index if you don't provide one but this isn't recommended.

Upvotes: 5

Related Questions