0

I need to put an if condition in the service_ids if it is empty or null. If it is empty or null, i should not pass the service_ids variable. How can i do it?

const formData = {
      car: form.value.car,
      remarks: form.value.remarks,
      if(form.value.service_ids !== null || form.value.service_ids !== []) {
        service_ids: form.value.service_ids.map((a: Service) => a.service_id ? a.service_id : []),
      }
}
Joseph
  • 7,042
  • 23
  • 83
  • 181
  • What's the problem with your current code? – Jack Bashford Jun 12 '19 at 02:03
  • @JackBashford. I can't do if statement in this if(form.value.service_ids !== null || form.value.service_ids !== []) { service_ids: form.value.service_ids.map((a: Service) => a.service_id ? a.service_id : []), } – Joseph Jun 12 '19 at 02:04
  • 2
    Possible duplicate of [Is there a standard function to check for null, undefined, or blank variables in JavaScript?](https://stackoverflow.com/questions/5515310/is-there-a-standard-function-to-check-for-null-undefined-or-blank-variables-in) – Heretic Monkey Jun 12 '19 at 02:23
  • 1
    Why not just set `service_ids` in a separate statement? – Heretic Monkey Jun 12 '19 at 02:25
  • @HereticMonkey. I’m passing formData as a whole – Joseph Jun 12 '19 at 02:27
  • 1
    Yeah, and? You can still do `const formData = {...}; if (form.value.service_ids !== null) { formData.service_ids = ...; } callWhatever(formData);`... – Heretic Monkey Jun 12 '19 at 02:33
  • If the problem is that you "can't do an if statement in this form", you're right. You can't do that. JS objects are key/value pairs. If statements are not valid keys. – jmargolisvt Jun 12 '19 at 02:55

2 Answers2

0

How about

const formData = {
    car: form.value.car,
    remarks: form.value.remarks
}

if(form.value.service_ids !== null || form.value.service_ids !== []) {
    formData.service_ids = form.value.service_ids.map(
        (a: Service) => a.service_id ? a.service_id : []
    );
}
Jairo
  • 306
  • 3
  • 12
0
var {car,remarks,service_ids} = form.value;
service_ids = service_ids && service_ids.length > 0
     ? service_ids.map((a:Service) => a.service_id ? a.service_id : undefined).filter(val=>!(!val || val === ""))
    : []
var formData = {
    car,
    remarks,
    service_ids
}

Phil.hsu
  • 86
  • 5