Home > database >  NextJs Map issue
NextJs Map issue

Time:12-19

I have a array that I want to map properly but I can't do it I always keep getting some error here is the array that I want to map

useful_links:
0: {Register Now: 'some linke'}
1:{Age Calculator: 'some link'}
2: {Join Now: 'some link'}
3:{Cantonment Board Official Website: 'some link'}

I want to map it as so I can use the key as text in anchor tag and those links as href

<a href={some link}>text that are key</a>

thanks in advance!

CodePudding user response:

You can use Object.entries() to get the list of keys / values from an object. For example, using a memo hook to produce a nicer array of objects...

const links = useMemo(
  () =>
    useful_links.flatMap((obj) =>
      Object.entries(obj).map(([text, href]) => ({
        href,
        text,
      }))
    ),
  [useful_links]
);

return (
  <ul>
    {links.map(({ href, text }, i) => (
      <li key={i}>
        <a href={href}>{text}</a>
      </li>
    ))}
  </ul>
);
  • Related