Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Want to Print Key Values of Object But it Prints Numbers in React

Want to print key values of object but it prints numbers. How to print on the screen key values. It prints key values but also prints numbers.

import Link from 'next/link';

export default function Home() {
  const menu = {
    lorem1: "/lorem1",
    ipsum1: {
      dolor2: "/dolor2",
      amet2: "/amet2",
    },
    loremm1: "/loremm1",
    ipsumm1: {
      dolor2: "/dolor2",
      amet2: "/amet2",
    },
  }

  return (
    <>
      <ul>
        {Object.entries(menu).map(([key, value]) => (
          <li key={key}>
            { typeof value === 'string' ? <Link href="/">{key}</Link> : key}
            <ul>
              {Object.entries(value).map(([innerKey, innerValue]) => (
                <li key={innerKey}>
                  <Link href="/">{innerKey}</Link>
                </li>
              ))}
            </ul>
          </li>
        ))}
      </ul>
    </>
  )
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

you can wrap the keys and values in a span or a div element when rendering them so that React treats them as a single child element. Here’s the modified code:



  return (
    <>
      <ul>
        {Object.entries(menu).map(([key, value]) => (
          <li key={key}>
            {typeof value === 'string' ? (
              <Link href="/">{key}</Link>
            ) : (
              <div>
                <span>{key}</span>
                <ul>
                  {Object.entries(value).map(([innerKey, innerValue]) => (
                    <li key={innerKey}>
                      <Link href="/">{innerKey}</Link>
                    </li>
                  ))}
                </ul>
              </div>
            )}
          </li>
        ))}
      </ul>
    </>
  );
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading