简体   繁体   中英

how to access variables declared in map outside it?

I have two map functions and have assigned its data to variables, I want to compare them

!followerLoading && (
    followersData.map((e) => 
        {
            const myFollowers = e.requested_profile.Userlink
        }
    )
)

!followingLoading && (
followingData.map((e) => 
    {
        const myFollowings = e.requesting_profile.Userlink
    }
)
)

const btntext = myFollowers===myFollowings ? "Following" : "Follow"

The mapping function will return an array as it iterates over. One way to tackle this problem is to compare the two arrays

const myFollowers = !followerLoading && (
    followersData.map((e) => e.requested_profile.Userlink )
)

const myFollowings = !followingLoading && (
followingData.map((e) => e.requesting_profile.Userlink)
)

const btntext = arr1.some(r=> arr2.includes(r))  ? "Following" : "Follow" 

You cannot access variables outside of their scopes. So do the following:

Declare myFollowers and myFollowings outside the scope of.map() and initialize them with some values.

Then you can assign values to those variables from the.map() methods.

let myFollowers = null;
let myFollowing = null;

followerLoading && (
    followersData.map((e) => 
        {
            myFollowers = e.requested_profile.Userlink
        }
    )
)
// Same for the other one

const btntext = myFollowers===myFollowings ? "Following" : "Follow";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM