We don't know what your array of objects look like so we have to guess:

So I guess this input:

const initState = [
    { id: 1, name: "bread", quantitiy: 50 },
    { id: 2, name: "milk", quantitiy: 20 },
    { id: 3, name: "water", quantitiy: 10 }
  ];

And I get this output:

It's completely flexible so if we have input:

const initState = [
    { id: 1, name: "bread", quantitiy: 50, location: "cupboard" },
    { id: 2, name: "milk", quantitiy: 20, location: "fridge" },
    { id: 3, name: "water", quantitiy: 10, location: "fridge" }
  ];

Then we get this output:

The most important thing is to map over the object values inside the map which maps over the state array:

{state.map((item) => (
        <tr key={item.id}>
          {Object.values(item).map((val) => (
            <td>{val}</td>
          ))}
        </tr>
      ))}

full demo below and on codePen: https://codepen.io/Alexander9111/pen/zYvEbML

I used a functional component but it would be very similar with a class-based component.

NOTE: you could also create a row component and then call that component inside the map over the state array. Inside this row component, you would map of the Object keys like I did and output table data elements. It's a balance between death by component (i.e. breaking down everything into smaller and smaller components nested inside each other) and fewer components which are too complex.

function MyTable() {
  const initState = [
    { id: 1, name: "bread", quantitiy: 50, location: "cupboard" },
    { id: 2, name: "milk", quantitiy: 20, location: "fridge" },
    { id: 3, name: "water", quantitiy: 10, location: "fridge" }
  ];
  const [state, setState] = React.useState(initState);

  return (
    <table>
      <tr key={"header"}>
        {Object.keys(state[0]).map((key) => (
          <th>{key}</th>
        ))}
      </tr>
      {state.map((item) => (
        <tr key={item.id}>
          {Object.values(item).map((val) => (
            <td>{val}</td>
          ))}
        </tr>
      ))}
    </table>
  );
}

ReactDOM.render(<MyTable />, document.getElementById("target"));
th,
td {
  border: 1px solid black;
  margin: 0px 0px;
  padding: 5px 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
<div id="target"></div>

Answer from Alex L on Stack Overflow
Top answer
1 of 4
11

We don't know what your array of objects look like so we have to guess:

So I guess this input:

const initState = [
    { id: 1, name: "bread", quantitiy: 50 },
    { id: 2, name: "milk", quantitiy: 20 },
    { id: 3, name: "water", quantitiy: 10 }
  ];

And I get this output:

It's completely flexible so if we have input:

const initState = [
    { id: 1, name: "bread", quantitiy: 50, location: "cupboard" },
    { id: 2, name: "milk", quantitiy: 20, location: "fridge" },
    { id: 3, name: "water", quantitiy: 10, location: "fridge" }
  ];

Then we get this output:

The most important thing is to map over the object values inside the map which maps over the state array:

{state.map((item) => (
        <tr key={item.id}>
          {Object.values(item).map((val) => (
            <td>{val}</td>
          ))}
        </tr>
      ))}

full demo below and on codePen: https://codepen.io/Alexander9111/pen/zYvEbML

I used a functional component but it would be very similar with a class-based component.

NOTE: you could also create a row component and then call that component inside the map over the state array. Inside this row component, you would map of the Object keys like I did and output table data elements. It's a balance between death by component (i.e. breaking down everything into smaller and smaller components nested inside each other) and fewer components which are too complex.

function MyTable() {
  const initState = [
    { id: 1, name: "bread", quantitiy: 50, location: "cupboard" },
    { id: 2, name: "milk", quantitiy: 20, location: "fridge" },
    { id: 3, name: "water", quantitiy: 10, location: "fridge" }
  ];
  const [state, setState] = React.useState(initState);

  return (
    <table>
      <tr key={"header"}>
        {Object.keys(state[0]).map((key) => (
          <th>{key}</th>
        ))}
      </tr>
      {state.map((item) => (
        <tr key={item.id}>
          {Object.values(item).map((val) => (
            <td>{val}</td>
          ))}
        </tr>
      ))}
    </table>
  );
}

ReactDOM.render(<MyTable />, document.getElementById("target"));
th,
td {
  border: 1px solid black;
  margin: 0px 0px;
  padding: 5px 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
<div id="target"></div>

2 of 4
0

item is an object from the array. So this object will have key(s) and value(s). You need to retrive those and show

For example suppose array is like

orderDetails=[{
  OrderID:1,
  CustomerID:'someName'
}]

Then in map you need to do

<table>
  {this.state.orderDetails.map((item =>
  <tr key={item.OrderID}>{item.CustomerID}</tr>
  ))}
</table>
🌐
Reddit
reddit.com › r/reactjs › how to map over 2 array of object in react and render to table
r/reactjs on Reddit: How to map over 2 Array of object in React and render to Table
March 21, 2022 -

how can i map over 2 Array of object in React and render to one Table

const [dataSetOne, setDataSetOne] = useState()
const [dataSettwo, setDataSetTwo] = useState()
``let URL1 = "http://api_url/users"
let URL2 = "http://api_url/users-card"
const promise1 = axios.post(URL1, inputValue , {headers: {'Content-Type': 'text/plain'}});
const promise2 = axios.post(URL2, inputValue , {headers: {'Content-Type': 'text/plain'}});
Promise.all([promise1, promise2]).then(function(values) {
  setDataSetOne(values[0]);
 setDataSetTwo(values[1]);
});

 <TableContainer>
      <Table>
        <TableHead>
          <TableRow>
            <TableCell>Dessert (100g serving)</TableCell>
            <TableCell align="right">Calories</TableCell>
            <TableCell align="right">Fat&nbsp;(g)</TableCell>
          </TableRow>
        </TableHead>
         <TableBody>

             <TableCell>{DataOne}</TableCell>
              <TableCell>{DataOne}</TableCell>
              <TableCell>{DataTwo}</TableCell>

       </TableBody>
      </Table>
    </TableContainer>
Top answer
1 of 3
22

You're doing

{item.mobile_open &&
          <tr className="test-td">
            <td>...</td>
          </tr>
        }

that prints false like <tr>false</tr> if mobile_open is false.

try

{item.mobile_open ?
              (<tr className="test-td">
                <td>...</td>
              </tr>) : null
            }

As for the div warning consider using React 16 Fragments

using React 16.0 fragment syntax

<tbody>
  {myList.map((item, i) => {
    return [
        <tr key={i} onClick={toggleMobileOpen.bind(this, i)}>
          <td className="toggler">
            {item.mobile_open && <ArrowUp />}
            {!item.mobile_open && <ArrowDown />}
          </td>
          <td>{item.elem_one}</td>
          <td>{item.elem_two}</td>
          <td>{item.elem_three}</td>
        </tr>,
        {item.mobile_open &&
          <tr className="test-td">
            <td>...</td>
          </tr>
        }

    ];
  })}
</tbody>

But I prefer the most recent React 16.2 Fragment Syntax

import React, { Fragment } from "react";

<tbody>
      {myList.map((item, i) => {
        return (
          <Fragment>
            <tr key={i} onClick={toggleMobileOpen.bind(this, i)}>
              <td className="toggler">
                {item.mobile_open && <ArrowUp />}
                {!item.mobile_open && <ArrowDown />}
              </td>
              <td>{item.elem_one}</td>
              <td>{item.elem_two}</td>
              <td>{item.elem_three}</td>
            </tr>
            {item.mobile_open &&
              <tr className="test-td">
                <td>...</td>
              </tr>
            }
          </Fragment>
        );
      })}
    </tbody>

More on fragments here

2 of 3
1

In React16 you are now able to return an array of components allowing you to remove the <div />.

The code would look something like :

 <tbody>
      {myList.map((item, i) => {
        return [
            <tr key={i} onClick={toggleMobileOpen.bind(this, i)}>
              <td className="toggler">
                {item.mobile_open && <ArrowUp />}
                {!item.mobile_open && <ArrowDown />}
              </td>
              <td>{item.elem_one}</td>
              <td>{item.elem_two}</td>
              <td>{item.elem_three}</td>
            </tr>,

            //This inline conditional makes it weird but this works
            ...[item.mobile_open &&
              <tr className="test-td">
                <td>...</td>
              </tr>
            ]
        ];
      })}
    </tbody>
Top answer
1 of 1
2

TL;DR Fully functionnal example :

//Columns defines table headings and properties to be placed into the body
const columns = [{ heading: 'Name', property: 'name' }, { heading: 'Age', property: 'age' }, { heading: 'Sex', property: 'sex' }, { heading: 'Breed', property: 'breed' },]

//Data is the array of objects to be placed into the table
const data = [{ name: 'Sabrina', age: '6', sex: 'Female', breed: 'Staffordshire' }, { name: 'Max', age: '2', sex: 'Male', breed: 'Boxer' }]

const App = props => <Table columns={columns} data={data} propertyAsKey='name' />

const Table = ({ columns, data, propertyAsKey }) => 
    <table className='table'>
        <thead>
            <tr>{columns.map(col => <th key={`header-${col.heading}`}>{col.heading}</th>)}</tr>
        </thead>
        <tbody>
            {data.map(item =>
                <tr key={`${item[propertyAsKey]}-row`}>
                    {columns.map(col => <td key={`${item[propertyAsKey]}-${col.property}`}>{item[col.property]}</td>)}
                </tr>
            )}
        </tbody>
    </table>
    
ReactDOM.render(<App/>, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.1/umd/react-dom.production.min.js"></script>
<div id='root'>


The main thing that would highly reduce this code is the map function. This function can be applied on an array, execute a callback on every item in the array and returns a new array.

By using it you can reduce the following code :

let headerRow = [];

columns.forEach(col => {
    headerRow.push(
        <th key={`header-${col.heading}`}>{col.heading}</th>
    );
});

Can be reduced to this with the exact same result :

const headerRow = columns.map(col => <th key={`header-${col.heading}`}>{col.heading}</th>)

You can now include this function directly into your JSX :

<thead>
    <tr>{columns.map(col => <th key={`header-${col.heading}`}>{col.heading}</th>)}</tr>
</thead>

And the same thing with nested mapping for the body :

<tbody>
    {data.map(item => 
        <tr key={`${item[key]}-row`}>
            {columns.map(col => <td key={`${item[key]}-${col.property}`}>{item[col.property]}</td>)}
        </tr>
    )}
</tbody>

Your full buildTable function is now reduced to the following :

buildTable = (columns, data, key) => {
    return (
        <>
            <thead>
                <tr>{columns.map(col => <th key={`header-${col.heading}`}>{col.heading}</th>)}</tr>
            </thead>
            <tbody>
                {data.map(item => 
                    <tr key={`${item[key]}-row`}>
                        {columns.map(col => <td key={`${item[key]}-${col.property}`}>{item[col.property]}</td>)}
                    </tr>
                )}
            </tbody>
        </>
    );
};

If you want to go a little further you can also delete this function and embed this code in your render function JSX. I will also convert your component into a stateless function, since you are not using any state value :

const Table = ({ columns, data, propertyAsKey }) => //Deconstructs your props
    <table className='table'>
        <thead>
            <tr>{columns.map(col => <th key={`header-${col.heading}`}>{col.heading}</th>)}</tr>
        </thead>
        <tbody>
            {data.map(item =>
                <tr key={`${item[propertyAsKey]}-row`}>
                    {columns.map(col => <td key={`${item[propertyAsKey]}-${col.property}`}>{item[col.property]}</td>)}
                </tr>
            )}
        </tbody>
    </table>

(You may add brackets and a return statement after the arrow sign, its up to you)

It is also not required to have a fragment as a parent element in your render, as long as there is a single element, it is fine :

class App extends React.Component {
  render() {
    return (
        <Table
          columns={columns}
          data={data}
          propertyAsKey='name' //The data property to be used as a key
        />
    );
  }
}

Your App component could also be converted to a stateless component:

const App = props => <Table columns={columns} data={data} propertyAsKey='name' />
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-build-an-html-table-using-reactjs-from-arrays
How to build an HTML table using ReactJS from arrays ? | GeeksforGeeks
November 10, 2023 - To build an HTML table from an array of elements using ReactJS, we can use the array map method. The map() method iterates through each element of the array and will convert it into a table row.
🌐
MDBootstrap
mdbootstrap.com › standard › material design for bootstrap 5 & vanilla javascript
Map Data from Object for Datatable on React - Material Design for Bootstrap
import React from 'react'; import { MDBDataTable } from 'mdbreact'; const DatatablePage = () => { const user = [ { username: "14a272ba-5bf8-4707-806f-847648550f4f", Attributes: [ { Name: "given_name", Value: "John" }, { Name: "family_name", Value: "Doe" }, { Name: "address", Value: "111 Main St" }, { Name: "city", Value: "New York" }, { Name: "state", Value: "New York" } ], UserCreateDate: `Wed Jun 19 2019 10:51:38 GMT-0400 (Eastern Daylight Time)` }, { username: "14a272ba-5bf8-4707-806f-847648550f4f", Attributes: [ { Name: "given_name", Value: "Jane" }, { Name: "family_name", Value: "Doe" },
🌐
Reddit
reddit.com › r/reactjs › how to display an array of objects row-by-row using react table?
r/reactjs on Reddit: How to display an array of objects row-by-row using React Table?
May 9, 2020 -

I want to display movies row-by-row without changing the data model.

Here's my code:

import * as React from "react";
import { useTable } from "react-table";

const borderStyle = {
  border: "1px dashed navy"
};

export default function App() {
  const data = React.useMemo(
    () => [
      {
        actor: "Johnny Depp",
        movies: [
          {
            name: "Pirates of the Carribean 1"
          },
          {
            name: "Pirates of the Carribean 2"
          },
          {
            name: "Pirates of the Carribean 3"
          },
          {
            name: "Pirates of the Carribean 4"
          }
        ]
      }
    ],
    []
  );
  const columns = React.useMemo(
    () => [
      {
        Header: "Actor",
        accessor: "actor",
      },
      {
        Header: "Movies",
        accessor: (row, index) => {
          console.log({ row });
          // i want to display this row-by-row instead of in 1-row without changing data model
          return row.movies.map(movie => movie.name);
        }
      }
    ],
    []
  );
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow
  } = useTable({ columns, data });
  return (
    <table {...getTableProps()}>
      <thead>
        {headerGroups.map(headerGroup => (
          <tr {...headerGroup.getHeaderGroupProps()}>
            {headerGroup.headers.map(column => (
              <th {...column.getHeaderProps()} style={borderStyle}>
                {column.render("Header")}
              </th>
            ))}
          </tr>
        ))}
      </thead>
      <tbody {...getTableBodyProps()}>
        {rows.map((row, i) => {
          prepareRow(row);
          if (i == 0) {
            console.log({ row });
          }
          return (
            <tr {...row.getRowProps()}>
              {row.cells.map((cell, j) => {
                if (i == 0 && j < 2) {
                  console.log({ cell, i, j });
                }
                return (
                  <td
                    {...cell.getCellProps()}
                    style={borderStyle}
                  >
                    {cell.render("Cell")}
                  </td>
                );
              })}
            </tr>
          );
        })}
      </tbody>
    </table>
  );
}

It currently looks like:

https://user-images.githubusercontent.com/16436270/80309485-00e48380-87f3-11ea-8040-9c08f4c2e866.PNG

Here's the direct link to it: https://codesandbox.io/s/modest-sanderson-z0keq?file=/src/App.tsx

My movie list is an array of objects so how will I display it beside actor name? So it looks like:

https://i.stack.imgur.com/xZBcJ.png

Edit: Solution can be found here

🌐
Medium
saurabhnativeblog.medium.com › rendering-a-table-in-react-from-a-json-array-using-object-keys-and-object-values-062046973780
Rendering a Table in React from a JSON Array using Object.keys and Object.values | by Saurabh Mhatre | Medium
October 23, 2023 - Next, we create an array of rows using `data.map(item => Object.values(item))`. This converts each object into an array of its values. In the JSX, we use a `<table>` element with `<thead>` and `<tbody>` sections.
🌐
30 Seconds of Code
30secondsofcode.org › home › react › components › data mapping components
Mapping data structures to React components - 30 seconds of code
June 18, 2024 - This way, you can create a table ... the keys and iterate over them, you'll combine Object.keys(), Array.prototype.filter(), Array.prototype.includes(), and Array.prototype.reduce()....
Find elsewhere
🌐
Scrimba
scrimba.com › articles › react-list-array-with-map-function
How to use Array.map to render a list of items in React
November 1, 2022 - This sets up the table and table headings and then after the heading row, we use Array.map to map over each book in the booksarray and pass it to the BookRow component. This has the effect of creating a new row for every element in the books array. You can see this example on CodePen. Sometimes an array will contain objects that also contain arrays as properties.
Top answer
1 of 2
1

Please change this part like below

vm.map(x => x.Virtual_Machines).map(y => (
  <tr>
    <td>{x.VM_Name}</td>
    <td>{x.VM_Location}</td>
    <td>{x.VM_Encryption}</td>
  </tr>
));
2 of 2
0

Your mapping is wrong, you have four levels / nesting in your JSON including Virtual_Machines, machine type, machine attributes and VM_Publisher_Info. You have mixed Virtual_Machines with machine attributes (VM_Location, VM_Encryption) that is wrong.

A similar case is:

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";
const data = [
  {
    name: "Jude",
    position: "Developer",
    experiences: [
      {
        id: 0,
        job: "React UI Developer",
        period: "2017-2018",
        description:
          "I love Creating beautiful Smart UI with React js and styled components"
      },
      {
        id: 1,
        job: "React/ Redux UI Developer",
        period: "2017-2018",
        description:
          "I love Creating beautiful Smart UI with React js and styled components"
      }
    ]
  }
];

class App extends React.Component {
  state = {
    data: []
  };
  componentDidMount() {
    console.log(data);
    this.setState({ data });
  }
  render() {
    const { data } = this.state;
    const resume = data.map(dataIn => {
      return (
        <div key={dataIn.name}>
          {dataIn.name}
          <ul>
            {dataIn.experiences.map(experience => (
              <li key={experience.id}>{experience.job}</li>
            ))}
          </ul>
          {dataIn.position}
        </div>
      );
    });

    return <div>{<React.Fragment>{resume}</React.Fragment>}</div>;
  }
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

mapping a nested array from json in React js

Top answer
1 of 2
2

One possible issue that I can see is not properly setting state in handleSubmit. You should do something like this:

handleSubmit = (e) => {
    e.preventDefault();
    const copyStateInvoices = [...this.state.invoices]
    copyStateInvoices.push({
        description: this.state.description,
        unit: this.state.unit,
        quantity: this.state.quantity
    })
    this.setState({
      invoices: copyStateInvoices,
    })
    //console.log(this.state.invoices[].description);

};

Component's state is immutable and if you try to change the values in state it will happen but react will not respect that. Read more about these fundamentals on react main website.

Thanks

2 of 2
0

Try with following changes.

Needs change in pushing objects to an array state

To push objects or values or numbers in react you should do something like below. The recommended approach to push values to an array in React is using prevState

   handleSubmit = (e) => {
       e.preventDefault();
       this.setState(prevState => ({
          invoices: [...prevState.invoices, {
          description: this.state.description,
          unit: this.state.unit,
          quantity: this.state.quantity
       }]
  }));
   };

And in .map you no need to do invoice[index] to get the value because you are doing .map on array so it gives you each object in loop so you can directly access invoice.unit directly and invoice[index].unit is not needed and not correct in loop

   const list = this.state.invoices.map((invoice, index) => {
    return (
        <tr key={index}>
            <td>{invoice.description}</td>
            <td>{invoice.unit}</td>
            <td>{invoice.quantity}</td>
            <td>{invoice.unit * invoice.quantity}</td>
        </tr>
    )
});
🌐
Stack Overflow
stackoverflow.com › questions › 45427163 › map-over-an-array-of-objects-to-create-a-table-in-reactjs
redux - Map over an array of objects to create a table in ReactJS - Stack Overflow
August 6, 2017 - import React from 'react' import { connect } from 'react-redux' import * as chrrdActions from '../../Redux/Chrrd' const Apis = props => (props.ChrList.list.map((item, i) => { return <tr key={item.objecj._id}> <td>{item._id}</td> <td>{item.Character_Name}</td> <td className="ellipsis">{item.Character_ID}</td> <td className="ellipsis">{item.Access_Token}</td> <td className="ellipsis">{item.Refresh_Token}</td> </tr> })); const ChrTable = props => ( <div> <table style={{ 'height': '40%', 'width': '600px', 'display': 'block' }}> <tbody> <tr> <th> Id </th> <th> Character Name </th> <th> Character ID</th> <th> Access Token </th> <th> Refresh Token</th> </tr> {Apis} </tbody> </table> </div> ) export default connect(state => ({ ChrList: state.ChrList }), { ...chrrdActions } )(ChrTable)
🌐
LabEx
labex.io › tutorials › react-object-table-view-38355
Create Dynamic Tables in React with Object Data | LabEx
const MappedTable = ({ data, ...[name]}</td> ))} </tr> ))} </tbody> </table> ); }; You can use the component by passing in an array of objects and a list of property names:...
🌐
C# Corner
c-sharpcorner.com › article › map-function-in-react
Map() Function in React
December 22, 2023 - This React component uses map() to transform the EmployeeDetails array into a list of <li> elements, each displaying a employee's name. The key attribute is crucial for React to efficiently manage dynamic lists.
🌐
YouTube
youtube.com › coding comics
Table in React Js || Create Table from Array of Objects in React Js - YouTube
In this video, I have explained how to create a table using array of object in react js.code : (https://github.com/AkajithAk/ReactUiYt/tree/main/src/ReactTab...
Published   February 4, 2023
Views   4K
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-render-an-array-of-objects-in-reactjs
How To Render An Array Of Objects In ReactJS? | GeeksforGeeks
April 12, 2025 - This React app renders a table with student data (Name, Marks, Phone) using React-Bootstrap. The data is stored in an array of objects and displayed dynamically using the map() method.
🌐
Shameem
shameem.me › home › how to render an array of objects in react?
How to Render an Array of Objects in React? - Shameem
March 31, 2023 - We will create a functional component called EmployeeList that takes in the array of employees as a prop and renders a table with the employee information. In this component, we first destructure the employees prop and use the map() method to create ...