0

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

2
  • Do you want not to refresh the page while in the map loop? Commented Nov 15, 2022 at 19:00
  • @Maxali No... I want to route to the next page i.e. pageB Commented Nov 15, 2022 at 19:04

2 Answers 2

1

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");
Sign up to request clarification or add additional context in comments.

6 Comments

What I really want to do is for each item in an array for which the status is inactive, I want to route to pageB
You have two inactive users. Do you want to router.push for both users?
Yes, also there can be many inactive users, but for simplicity, I have used only 3 items in an array
That means, the first router.push will navigate to pageB which i think makes the next router.push useless. Do you mean to navigate to pageB and send all inactive users at the sametime.
No, I want to route to pageB one at a time
|
0

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"}
]

1 Comment

it is required. actually it is a big object but for simplicity I have used only two properties. I will add more

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.