How can I map through two arrays in React at the same time?

Viewed 5058

I am a beginner in React. I am using the json placeholder to fetch data using axios. I have two arrays in the state.

state = {
                posts : [],
                images : []

       };

After getting the data through axios I am using set state up update the value. Now, I want it all displayed in a card. If it were just one array I would've used map to display the content. Now I want an image from the images array to be displayed with each post. How could I go about this?

2 Answers

You can create single array out of two array in this way.

const postsWithImage=this.state.posts.map(post=>{
return {
...post,
img: this.state.images.find(img=> img.id===post.imgid) // or some relation between posts and images
}

})

now further map the postsWithImage

instead of separate arrays you could combine them and loop through like this :

const renderPosts = ()=>{
  return this.state.posts.map(post,index=>{
      return(
          <Card
             postImage={post.image}
             postData={post.data}
          />
       )
})
}

But if you are insisting on keeping them separate than you could do a nested loop like :

const templates = {
  template1: {
    items: [1, 2]
  },
  template2: {
    items: [2, 3, 4]
  },
};

const App = () => (
  <div>
    {
      Object.keys(templates).map(template_name => {
        return (
          <div>
            <div>{template_name}</div>
            {
              templates[template_name].items.map(item => {
                return(<div>{item}</div>)
              })
            }
          </div>
        )
      })
    }
  </div>
);
Related