lams
lams

Reputation: 372

javascript optional chaining on just one parameter

Is there a way to achieve optional chaining on just a single parameter ?

setAllProperties(
    Object.values(users).flatMap(({ properties }) =>
      Object.values(properties)
    )
  );

I want to make sure that the properties folder exist in the user folder. something like {properties?... [ I have only used tis when there is another folder, like properties?.property_id]

Some users in my database do not have any properties added, to their account, so they will not have a properties folder.

This is causing my page to crash "cannot convert null object". How can I use optional chaining here?

I tried putting the question mark, but the syntax is wrong

Upvotes: 0

Views: 72

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370879

Optional chaining only works when you're trying to access a member of an object directly. But Object.values(properties) does not directly access a member; the access is done inside the Object.values function, which you can't change. So optional chaining won't work here. You'll need something a bit more verbose.

setAllProperties(
  Object.values(users).flatMap(({ properties }) =>
    properties ? Object.values(properties) : []
  )
);

Upvotes: 2

Related Questions