1

I'm trying to write a map function to return a navbar. I have an array/dictionary that I want to loop through using the map function that looks something like

[['Text', './link.html'],
 ['Text2', './link2.html'],
 ['Text3', './link3.html']]

or else

{'Text', './link.html',
 'Text2', './link2.html',
 'Text3', './link3.html'}

Whatever type I need to loop through doesn't matter, I just want to loop through sets of 2, ideally I'd want to use tuples, but it doesn't look like that's an option from what I've read.

When looking at solutions that use the dict/object method, I don't know how to access both the key and the value. For ex.

var NavBar = (props) => {

    return (
        <div id="NavMain">
            {Object.keys(props.links).map((link,index) => {
                return <NavBarItem link={link} />
                {/* Where do I access the key? */}
            })}
        </div>
    )}

If I try to map this as a 2d array, my IDE is showing some error lines underneath 'row', 'text' and '/>' in the code below

var NavBar = () => {
      
    return (
        <div id="NavMain">
            {this.props.links.map((row,index) => {
                return <NavBarItem link=row[1] text=row[0] />
            })}
        </div>
    )}

Other solutions I've looked up are really messy. I'm wondering if there's a clean way to use the map function over sets of 2.

Sam
  • 277
  • 1
  • 27
  • 91
  • The second approach is pretty normal. The only "messy" thing is that you have to use indexes but given that you have two items, it's to be expected. – VLAZ Jul 12 '19 at 08:15
  • @Jacob, any luck on integrating a solution :) – Cool Guy Jul 12 '19 at 22:25

2 Answers2

1

You can use array destructuring inside the .map() like this:

So assuming you have a data set of an array of arrays:

const arr = [
     ['Text', './link.html'],
     ['Text2', './link2.html'],
     ['Text3', './link3.html']
]

var NavBar = (props) => {
    return(
      <div id="NavMain">
        {arr.map(([text, link]) => {
           return <NavbarItem link={link} text={text}/>
        })}
      </div>
    )
}

We know the first item is text and the second item is link as expected.

See sandbox for working example: https://codesandbox.io/s/stoic-payne-9zdp3

Cool Guy
  • 13,461
  • 2
  • 13
  • 32
0

You almost had it. Try this:

/*
props.links = {
    'Text' : './link.html',
    'Text2' : './link2.html',
    'Text3' : './link3.html'
}
*/

var NavBar = (props) => {
    return (
        <div id="NavMain">
            {Object.keys(props.links).map((key, index) => {
                return <NavBarItem link={props.links[key]} text={key}  />
            })}
        </div>
    )
}
Chiranjib
  • 1,549
  • 2
  • 16
  • 28