mrpbennett
mrpbennett

Reputation: 1956

printing out items from an array within an array of objects

I am trying to create some pills for a card display. I have an array of objects which I am mapping over to produce them on the page. Within the objects I have an array called tech which has something like tech: ['python', 'react.js'] etc.

something like this:

    const data = [
        {
          imgUrl: "https://images.unsplash.com/photo-1551882547-ff40c63fe5fa?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80",
          description: 'oifonefpempfewpvpewmpew',
          title: "Some project name",
          tech: ["python", "react.js"],
        },
{
          imgUrl: "https://images.unsplash.com/photo-1551882547-ff40c63fe5fa?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80",
          description: 'oifonefpempfewpvpewmpew',
          title: "Some project name",
          tech: ["python", "react.js"],
        },
    ]

I have mapped over that array like so.

<div className="">
  {data.map(tech => (
    <span className="inline-block bg-gray-200 rounded-full px-3 py-1 text-sm font-semibold text-gray-700 mr-2">
      {tech.tech}
    </span>
  ))}
</div>

Which it prints out the items, but it doesnt split them up into seperate pills just prints the array in one pill.

I am using Gatsby for my project

How can i split them up?

Upvotes: 0

Views: 57

Answers (2)

Dev Yego
Dev Yego

Reputation: 553

From your code, you can see that you're just outputting the array at {tech.tech}: Try this, assuming you already created the component as Pill and data hold the array of project objects; I am also assuming this is a project component and the Pill component lives in it, then:

<div className="">
    {data.map(project => (
        <span className="inline-block bg-gray-200 rounded-full px-3 py-1 text-sm font-semibold text-gray-700 mr-2">
            {project.tech.map(t => <Pill tech={t} />)}
        </span>
    ))}
</div>

Upvotes: 0

Anurag Srivastava
Anurag Srivastava

Reputation: 14413

You need to have another .map();

<div className="">
  {data.map(el => (
    el.tech.map(currTech => (
      <span className="inline-block bg-gray-200 rounded-full px-3 py-1 text-sm font-semibold text-gray-700 mr-2">
        {currTech}
      </span>
    ))        
  ))}
</div>

Upvotes: 1

Related Questions