DanoSVK
DanoSVK

Reputation: 55

Loop through 2D array in React

I am quite new to React so I would like to ask you, if there is any way to loop through 2D array in React.

Example of 2D array:

const db = {
    "1": {
        "1": "aaa",
        "2": "bbb",
        "3": "ccc"
    },            
    "two": {
        "1": "ddd",
        "2": "eee"
    }
};

My pseudo code:

for(i = 1; i < db.lenght; i++){
     for(j = 1; j < db[i].lenght; j++){
          console.log(db[i][j]);
     }
}

But I don't know how to render it in React, for example in <ul> tag.

Upvotes: 1

Views: 7634

Answers (4)

Petr Broz
Petr Broz

Reputation: 9942

In React it's common to use array methods like Array#map. In your React component code, if outerArray was an arrray of arrays, you could process it this way:

return (
    <ul>
        {outerArray.map((innerArray) => (
            <li>
                {innerArray.map((item) => <li>{item}</li>)}
            </li>
        ))}
    </ul>
);

Upvotes: 3

Arup Rakshit
Arup Rakshit

Reputation: 118271

You can iterate the db object as below, and show them in a list.

const db = {
  "1": {
    "1": "aaa",
    "2": "bbb",
    "3": "ccc"
  },
  two: {
    "1": "ddd",
    "2": "eee"
  }
};

function App() {
  return (
    <ul className="App">
      {Object.keys(db).map(keyOuter => {
        return Object.keys(db[keyOuter]).map(keyInner => {
          return (
            <li key={`${keyInner}-${keyOuter}`}>{db[keyOuter][keyInner]}</li>
          );
        });
      })}
    </ul>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>


<div id="root"></div>

Upvotes: 2

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

It's simple. Return list like this inside your loop:

<li>{db[i][j]}</li>

myList() {
  let list = []
  for(i = 1; i < db.lenght; i++){
     for(j = 1; j < db[i].lenght; j++){
          console.log(db[i][j]);
       list.push(<li key={i+'-'+j}>{db[i][j]}</li>)
       // when rendering list of array elements, wee need unique key
     }
  }
  return list
}

render() {
  return <ul>{this.myList()}</ul>
}

Upvotes: 2

trixn
trixn

Reputation: 16309

It is easiest to use Array.prototype.map() to loop through arrays inside jsx:

render() {
    return (
        <ul>
            {db.map(entries => (
                <li>
                    <ul>
                        {entries.map(entry => (
                            <li>{entry}</li>
                        ))}
                    </ul>
                </li>
            ))}
        </ul>
   );
}

Upvotes: 0

Related Questions