sanchit
sanchit

Reputation: 49

Map inside a map - Javascript

I have tried putting a map inside a map. The innermost map is running multiple times because of the map surrounding it. The requirement is to get the links mapped to the description (I've used # for some links).

Below is the data:

    {
        title: 'test',
        description: ['Team', 'History', 'Contact us', 'Locations'],
        linkto: ['#','#','#','#'],
    },
    {
        title: 'Categories',
        description: ['test', 'test2', 'test3', 'test4', 'test5'],
        linkto: ['#','#','#','#'],
    },
    {
        title: 'Legal',
        description: ['Privacy policy', 'Terms of use'],
        linkto: ['#','#',],
    },
    {
        title: 'Social',
        description: ['Facebook', 'Twitter', 'Instagram', 'Youtube', 'LinkedIn'],
        linkto: ['https://www.facebook.com', 'https://twitter.com/', 'https://www.instagram.com/', 'https://www.youtube.com/', 'https://www.linkedin.com']
    },
];

**Below is the mapping code:********************************************

<Grid container spacing={4} justify="space-evenly">
                    {footers.map((footer) => (
                        <Grid item xs={6} sm={3} key={footer.title}>
                            <Typography variant="h6" color="textPrimary" gutterBottom>
                                {footer.title}
                            </Typography>
                            <ul>
                                {footer.description.map((item, index) => (
                                        footer.linkto.map((link, subindex) => (
                                            <Link key={subindex} href={link} variant="subtitle1" color="textSecondary">
                                                <li key={index}>{item}</li>
                                            </Link>
                                        ))
                                ))}
                            </ul>
                        </Grid>
                    ))}
                </Grid>

Upvotes: 1

Views: 2115

Answers (1)

charlietfl
charlietfl

Reputation: 171679

Assuming they each have same lengths for each item just map one of the arrays and use the index to get the value from the one you are not mapping.

Also for valid markup the <li> needs to be outside as child of the <ul> not nested as child of <Link> and you don't need a key on the inner element

Something like:

{footer.description.map((item, index) => (
    <li key={index}>
      <Link href={footer.linkTo[index]} variant="subtitle1" color="textSecondary">
         {item}
       </Link>  
     </li>                                   
)}} 

Upvotes: 1

Related Questions