Home > Software engineering >  mapping within another map and printing multiple properties on object
mapping within another map and printing multiple properties on object

Time:06-20

In this code, everything prints out right except for my "flavors" is only returning one property value (the one at the index of 0] in the browser instead of the array it is supposed to. I should be showing 3 flavors per entry. I believe the answer would be to map that array within my current array of entries, but I am unsure as to how to write this out. Any help or tips are appreciated!

return (
  <>
    <article className="entries">
      {
        entries.map(entry => {
          return <section key={`entry--${entry.id}`} className="entry">
            <div>
              <ul>
                <div><img src={entry.image} height="300" /></div>
                <li>Name: {entry.name}</li>
                <li>Brewing Method: {entry.brewing_method.type}</li>
                <li>Grind Setting: {entry.grind_setting}</li>
                <li>Rating: {entry.rating}</li>
                <li>Flavors: {entry?.flavor_profile[0]?.name}</li>
                <li>Notes: {entry.notes}</li>
              </ul>

CodePudding user response:

You'll need a nested map() either to render a nested list, or just a string of flavors

For just a string of 3 flavors regardless of the actual number you can slice() and then map() the name property and finally join().

<li>Flavors: {entry.flavor_profile?.slice(0, 3).map(({ name }) => name).join(', ')}</li>

For a list you'll need to create a nested <ul> populated with the mapped flavor <li> elements

return (
  <>
    <article className="entries">
      {
        entries.map(entry => {
          return (
            <section key={`entry--${entry.id}`} className="entry">
              <div>
                <ul>
                  <div><img src={entry.image} height="300" /></div>
                  <li>Name: {entry.name}</li>
                  <li>Brewing Method: {entry.brewing_method.type}</li>
                  <li>Grind Setting: {entry.grind_setting}</li>
                  <li>Rating: {entry.rating}</li>
                  <li>Flavors:
                    <ul>
                      {
                        entry.flavor_profile?.map(({ name }) => (
                          <li>{name}</li>
                        ))
                      }
                    </ul>
                  </li>
                  <li>Notes: {entry.notes}</li>
                </ul>
              </div>
            </section>
          )
        })
      }
    </article>
  </>
);
  • Related