Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I iterate nested arrays in a React component?

I have a multidimensional array: an array results containing 18 arrays row, each containing 6 numbers.

I want to render this as a table. The logic would be

results.each as (row)
     <tr>
         row.each as (number)
               <td>number</td>
     </tr>

But I can't figure out how you'd write this in JSX.

const Resultset = props => (
    {props.rows.map(rows => {
        <tr>
            {rows.map(number => <td>{number}</td>)}
        </tr>
    })}
);

But that's not right. What's the procedure for this, how do you nest the map calls and interpolations?

like image 232
GreenTriangle Avatar asked Feb 07 '16 05:02

GreenTriangle


People also ask

How do you iterate an array of arrays in Reactjs?

To loop through an array of objects in React:Use the map() method to iterate over the array. The function you pass to map() gets called for each element in the array. The method returns a new array with the results of the passed in function.

How do you access nested objects in React?

If we want to access all the values of nested objects then we have to use recursion to access each and every level of that object. And it can get more complicated according to the nesting of the object. That why we have to use recursion to get all the values and access the whole nested object.


1 Answers

One way to do it

var arr = [ [ 2, 3, 4, 5, 6, 7 ],
  [ 8, 9, 10, 11, 12, 13 ],
  [ 14, 15, 16, 17, 18, 19 ],
  [ 20, 21, 22, 23, 24, 25 ],
  [ 26, 27, 28, 29, 30, 31 ],
  [ 32, 33, 34, 35, 36, 37 ],
  [ 38, 39, 40, 41, 42, 43 ],
  [ 44, 45, 46, 47, 48, 49 ],
  [ 50, 51, 52, 53, 54, 55 ],
  [ 56, 57, 58, 59, 60, 61 ],
  [ 62, 63, 64, 65, 66, 67 ],
  [ 68, 69, 70, 71, 72, 73 ],
  [ 74, 75, 76, 77, 78, 79 ],
  [ 80, 81, 82, 83, 84, 85 ],
  [ 86, 87, 88, 89, 90, 91 ],
  [ 92, 93, 94, 95, 96, 97 ],
  [ 98, 99, 100, 101, 102, 103 ],
  [ 104, 105, 106, 107, 108, 109 ] ];

var Hello = React.createClass({
  tablerows: function() {
    return this.props.arr.map(rows => {
        var row = rows.map(cell => <td>{cell}</td>); 
        return <tr>{row}</tr>;
    });
  },
  render: function() {
    return <table>{this.tablerows()}</table>;
  }
});

ReactDOM.render(
  <Hello arr={arr} />,
  document.getElementById('container')
);

In action: https://jsfiddle.net/69z2wepo/30476/

like image 110
manonthemat Avatar answered Oct 04 '22 13:10

manonthemat