-1

I have this deeply nested value

eventsubcategoryvalue: data.body.spending.requestspend==='y' ? data.body.spending.allowspend : chargeamount

so here eventsubcategoryvalue is decided on basis of result of the ternary operator. I want to use optional chaining here instead of having this complex nested thing. How can I re write it? I am unable to understand even after going through the MDN doc.

How can one rewrite this with optional chaining?

Jelly
  • 1
  • 1
  • I don't see how optional chaining can give you the same behavior as the ternary operator. – Robby Cornelissen Jul 01 '22 at 07:33
  • @RobbyCornelissen I don't want to replace ternary operator using optional chaining. I just want to simply the deeply nested values using it. Is this possible somehow? Can `eventsubcategoryvalue: data.body.spending.requestspend==='y' ? data.body.spending.allowspend : chargeamount` be re written using optionalchaining? – Jelly Jul 01 '22 at 07:41
  • "The way I wrote it, showed error". What error? Maybe it needs `()` ? `eventsubcategoryvalue: (data.body.spending.requestspend==='y' ? data.body.spending.allowspend : chargeamount)` – Suraj Rao Jul 01 '22 at 07:41
  • @SurajRao no, what I meant was when i tried putting optional chaining then it showed error, so I couldn't figure out how optional chaining can be put in this. – Jelly Jul 01 '22 at 07:45
  • 1
    optional chaining is only for null safety. You need to check for a specific value. So not the tool for the job – Suraj Rao Jul 01 '22 at 07:47
  • Is data.body.spending` never guaranteed then? Is that what you need the chaining for? – Andy Jul 01 '22 at 07:47
  • @Andy yes yes,the data is being fetched from api so there is a chance that it might not exist at times – Jelly Jul 01 '22 at 07:53
  • Do you want to set defaults if that information isn't available, or just not run that code? For defaults you might do [something like this](https://jsfiddle.net/hcxw8k2L/) (try removing the `spending` part of the data). @Jelly – Andy Jul 01 '22 at 08:01

1 Answers1

0

Try

(eventsubcategoryvalue) ? ( data.body.spending.requestspend === 'y' ? data.body.spending.allowspend : chargeamount ) : chargeamount 
  • What this is doing is checking if the first () is a truthy value, if it is it will check the next step which is data.body.... , if it = y then it will see if allowedspend is a truthy value. if it is it will charge amount, if everything is a falsy value, it will return chargeamount. Really don't know the use case for this but based on what you sent I think this is a way to get that. – Jerome Moores Jul 01 '22 at 15:24
  • 1
    You should update your answer to include the explanation instead of posting it in comment – ray Jul 02 '22 at 03:16