xivilo
xivilo

Reputation: 29

Iterate an value in the object and Filter them if is not null

So I want to iterate some users, and each of those users has an object name vehicles and I want to iterate the users, and also then iterate the vehicles value within the object, but the problem is that the second iteration that iterates the vehicles sometimes gives an error because a user might have null users, and it doesn't iterate them and stops the loop by giving an error, what I want to do is, skip the iteration on that value if it is null.

Here is my code:

const c = clients.clients.filter((c) => 
  c.vehicles.map((v) => console.log(v._id))
);

Error message: Uncaught TypeError: Cannot read properties of null (reading 'map')

Upvotes: 0

Views: 24

Answers (2)

Mohammad
Mohammad

Reputation: 790

try this :

const c = clients.clients.filter((c) => {
  if(!c) return false;
  if(!c.vehicles) return false;
  return c.vehicles.map((v) => console.log(v._id))
  }
);

Upvotes: 0

albjerto
albjerto

Reputation: 571

Take a look at the optional chaining operator ?.

In your case, the loop would become

const c = clients.clients.filter(c => 
  c.vehicles?.map(v => console.log(v._id));
);

To give a brief explanation of the operator, when used on a property that might not be present (I'm assuming vehicles in your case), instead of raising an error it short-circuits the evaluation to undefined, which is a falsy value, and it is therefore filtered out by .filter.

Upvotes: 1

Related Questions