Home > Software engineering >  how to access variables declared in map outside it?
how to access variables declared in map outside it?

Time:11-26

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"

CodePudding user response:

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" 

CodePudding user response:

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";
  • Related