Home > Software design >  Mapping through an array and Routing
Mapping through an array and Routing

Time:11-16

I have an array of objects like below -

const studentDetails = [
    {id:1, name:"Mike", stream:"Science", status:"active"},
    {id:2, name:"Kelly", stream:"Commerce", status:"inactive"},
    {id:3, name:"Bob", stream:"Law", status:"inactive"},
]

What I want to do is map through the array and route to another page when the status is inactive.

studentDetails.map(studentDetail => {
    if(studentDetail.status === 'inactive'){
        router.push("/pageB")
    }
})

My doubt here is that when we route to pageB when the id is 2, how will I continue the loop for id=3

Many Thanks

CodePudding user response:

Find the first inactive user using Array.find instead of Array.map

const studentDetails = [
    {id:1, name:"Mike", stream:"Science", status:"active"},
    {id:2, name:"Kelly", stream:"Commerce", status:"inactive"},
    {id:3, name:"Bob", stream:"Law", status:"inactive"},
]

let inactiveUser = studentDetails.find(user => user.status === "inactive");

console.log(inactiveUser);

// inactiveUser can be null, so we have to check first.
if (inactiveUser) router.push("/pageB");

CodePudding user response:

I'm wondering why that {id:3, status:"inactive"} is needed. You can omit that code if it is the same as the other one except id. Like this:

const studentDetails = [
    {id:1, status:"active"},
    {id:2, status:"inactive"}
]
  • Related