Thang Ho Minh
Thang Ho Minh

Reputation: 13

Map 2 arrays of object to make a loop

I have these codes

    import React, { Component } from 'react'
    import './RightContent.css'

    class RightContent extends Component {
    render() {
    const albumdata = this.props.albumdata;
    const albumthumbnail = this.props.albumthumbnail;
    return (

        <div class="content2">
        {albumthumbnail.map(data => (

            <div class="albumcontainer">
                <div class="albumitem">
                    <img src={data.url}></img>
                    <div class="description">{data.title}</div>
                </div>  
           </div>

        ))}
        </div>

    );
}

The problem is that I would to make a loop of album item with image and title, the albumdata contains titles of the albums, while albumthumbnail holds the first image of the album, but I can't do the map below the albumthumbnail.map .

I would like to make a loop in div to display albums with details coming from two arrays of objects. But it seems impossible.

Upvotes: 1

Views: 68

Answers (2)

Thang Ho Minh
Thang Ho Minh

Reputation: 13

I have done thanks to your answer. Thanks to the 2nd parameter that I could do it!

return (
            <div class="content2">
            {albumthumbnail.map((data, index) => (
                <div class="albumcontainer">
                    <div class="albumitem">
                        <img src={data.thumbnailUrl}></img>
                        <button class="description" onclick="showDetail()">{albumdata[index].title}</button>
                    </div>  
               </div> 
            ))}
            </div>

        );

Upvotes: 0

Nicholas Tower
Nicholas Tower

Reputation: 84982

The function that you pass into map actually gets more than just one parameter passed to it. The second parameter is the index. So you can use that to grab the corresponding value from your other array.

albumthumbnail.map((thumbnail, index) => (
  // Do something with thumbnail, and also something with albumdata[index]
))

I'm assuming the two arrays are exactly the same length; if they aren't you'll need some more safeguards.

Upvotes: 1

Related Questions