1

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.

3
  • 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? Commented Aug 29, 2018 at 19:54
  • Yes, for example into <ul>, I will update question. 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. Commented Aug 29, 2018 at 20:10

4 Answers 4

3

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>
);
Sign up to request clarification or add additional context in comments.

Comments

2

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>

13 Comments

@DanoSVK You understood what is going on in the above code? Else, shoot questions.
shoot questions? your wording makes me sharp. :)
It is to note that looping through object keys has an arbitrary order. If you want to render the entities in a defined order you have to sort the keys before or better make the data source an array.
Good night guys!
Yes I understand :) It is like nested map function. I just wonder if order of items will be always same as in array as @trixn said.
|
2

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>
}

3 Comments

Thank you and what happens if one of my index was string and not number (updated question)?
Thank you, that's great, but one more question as I said what happens if my second index is string and not number? What to do in that scenario?
Nothing difference in javascript and react. Just think what will happen, then you may build your programming skill better. Try and do some more effort. That's what I suggest you to follow. To answer: you need to use other built in function like map. You may follow @arup answer.
0

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>
   );
}

2 Comments

@ArupRakshit OP wrote that it is an array which is also shown by how his loops are constructed. Looping over an object like this wouldn't work. The "object" is possibly just what a console log gave to OP. This looks like an object while it is an array.
check const db = {.. The OP didn't explain it correctly, probably very new to JS, so the OP has no control on the terms in JS. By looking at the coding style, someone who spent more time in JS will measure the proficiency of the askers, and that little help we should offer being an answerer.. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.