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.

trixn
  • 12,247
  • 1
  • 21
  • 42
DanoSVK
  • 55
  • 1
  • 7
  • 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 Aug 29 '18 at 19:54
  • Yes, for example into
      , I will update question.
    – DanoSVK Aug 29 '18 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 Aug 29 '18 at 20:10

4 Answers4

3

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>
Arup Rakshit
  • 109,389
  • 25
  • 234
  • 293
  • @DanoSVK We're glad to help you. – Bhojendra Rauniyar Aug 29 '18 at 20:10
  • 1
    @DanoSVK You understood what is going on in the above code? Else, shoot questions. – Arup Rakshit Aug 29 '18 at 20:11
  • 1
    shoot questions? your wording makes me sharp. :) – Bhojendra Rauniyar Aug 29 '18 at 20:12
  • 2
    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. – trixn Aug 29 '18 at 20:12
  • 1
    Good night guys! – Bhojendra Rauniyar Aug 29 '18 at 20:17
  • 1
    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. – DanoSVK Aug 29 '18 at 20:22
  • @DanoSVK A defined order is not guaranteed when iterating over object keys. Only arrays have a defined order. Objects are not made for being sorted in any way. If you want the order to be always determined you have to make sure that data source is an array or you have to sort the object keys before iterating them. Also see https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order – trixn Aug 29 '18 at 20:27
  • @trixn But it says that "using the Map object could be an alternative. A Map shares some similarities with an Object and guarantees the keys order" so if I use map function like above it should be always same, right? – DanoSVK Aug 29 '18 at 20:30
  • @DanoSVK Yes it will be. – Arup Rakshit Aug 29 '18 at 20:30
  • @DanoSVK The `map()` function is not to confuse with a `Map` object. An array has a `map()` function that will call the provided handler to construct a new array. Interating is done in the order of the elements in the array. A `Map` object is quite new and not supported in older browsers but it may serve your needs. But probably an array is sufficient. – trixn Aug 29 '18 at 20:33
  • @DanoSVK The problem with the above code in the answer is that `Object.keys(db)` is an array where the keys have no guaranteed order. It could be `["two", "1"]` or `["1", "two"]`. While in practice it usually has the same order this is not a fact you can rely on because it is not guaranteed by the javascript interpreter. If your entities are in a certain order better use an array. – trixn Aug 29 '18 at 20:36
  • Arup Rakshit says it will be always same and @trixn says that it don't have to be always same, Im bit confused :D – DanoSVK Aug 29 '18 at 20:36
  • @DanoSVK See https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order to understand why object keys have no guaranteed order. – trixn Aug 29 '18 at 20:37
1

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>
}
Bhojendra Rauniyar
  • 73,156
  • 29
  • 131
  • 187
  • Thank you and what happens if one of my index was string and not number (updated question)? – DanoSVK Aug 29 '18 at 19:58
  • 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? – DanoSVK Aug 29 '18 at 20:03
  • 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. – Bhojendra Rauniyar Aug 29 '18 at 20:07
1

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>
);
Petr Broz
  • 5,408
  • 2
  • 12
  • 21
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>
   );
}
trixn
  • 12,247
  • 1
  • 21
  • 42
  • @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. – trixn Aug 29 '18 at 20:08
  • 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.. :) – Arup Rakshit Aug 29 '18 at 20:09