1

I looked at some other answers on stackoverflow and haven't been able to find one that answers my question.

I havea a variable toolShortcuts that is an object made up of arrays of objects:

toolShortcuts = {
  1: [{key: "s", description: "click this to scale"}],
  2: [{key: "delete", description: "click this to delete"}, {key: "backspace",description: "click this to delete"}]
}

I'm trying to return some HTML for every element in the object (3 elements in the above object). Since I'm using a for loop with a return statement, only the first elements of each array are being displayed (2 out of the 3 elements). How can I display all three elements?

  <Container>
    { Object.values(toolShortcuts).map((shortcuts) => {
        for (let i in shortcuts) {
          return (
            <Row>
              <$DescriptionCol>{shortcuts[i].description}</$DescriptionCol>
              <$ButtonCol lg="3">{shortcuts[i].key}</$ButtonCol>
            </Row>
          )
        }
      })
    }
  </Container>
AKang123.
  • 405
  • 6
  • 15
  • 1
    Please tag the template or framework you are using - looks like React – mplungjan Dec 22 '20 at 18:47
  • 1
    `[key: "s", description: "click this to scale"]` should probably be `[{key: "s", description: "click this to scale"}]` – Anchor Dec 22 '20 at 18:54
  • also, `return` inside a `for` just bails out of the loop. You're already using `map` just above, you could use map again and it would work. Maybe throw a `flatMap` in there. – Emile Bergeron Dec 22 '20 at 18:55
  • Does this answer your question? [How do I use for loops with react?](https://stackoverflow.com/questions/46908480/how-do-i-use-for-loops-with-react) – Emile Bergeron Dec 22 '20 at 18:57
  • @EmileBergeron thanks for your help! Can you please confirm that I'm understanding your suggestion correctly. This is what I've implemented now: ```shortcuts.map((shortcut) => { return ( <$DescriptionCol>{shortcut.description}$DescriptionCol> <$ButtonCol lg="3">{shortcut.key}$ButtonCol> ) }) ``` – AKang123. Dec 22 '20 at 19:09
  • 1
    You'll need to use `flatMap` instead of the first `map` if you're going to nest both loops. Otherwise, yes, it's what I meant. – Emile Bergeron Dec 22 '20 at 19:13

1 Answers1

0
<Container>
    {Object.values(toolShortcuts).map((shortcuts, indexTool) => (
        <React.Fragment key={indexTool}>
            {shortcuts.map((shortcut) => (
                <Row key={shortcut.key}>
                    <$DescriptionCol>{shortcut.description}</$DescriptionCol>
                    <$ButtonCol lg="3">{shortcut.key}</$ButtonCol>
                </Row>        
            ))}
        </React.Fragment>
    }
</Container>
Marcus Yoda
  • 243
  • 1
  • 8