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.
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.
- 1 A loop is a loop... that code is valid javascript, so there is no difference in react... do you mean how to loop and render the values in react? – ageoff Commented Aug 29, 2018 at 19:54
- Yes, for example into <ul>, I will update question. – DanoSVK Commented Aug 29, 2018 at 19:56
-
@DanoSVK
db
is not an array. It is an object. Please correct your formulation of the question. Looping through object entities is quite different. – trixn Commented Aug 29, 2018 at 20:10
4 Answers
Reset to default 3In React it's mon to use array methods like Array#map. In your React ponent 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>
);
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./ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
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>
}
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>
);
}