5
  let notStudent, name, isRegistered
  if (studentDetail && studentDetail.fields) {
    ({ notStudent, name, isRegistered } = studentDetail.fields)
  }

Is there a way to write this logic without an if statement or in a succinct way?

Henok Tesfaye
  • 8,287
  • 13
  • 47
  • 84

2 Answers2

6

You can destructure in this way. The tricky thing is when there is no fields property on studentDetail then javascript can throw an error, to tackle that case, you can set default empty object using || operator.

let studentDetail = {
  fields: {
    notStudent: '1',
    name: '2',
    isRegistered: true
  }
}

let {
  notStudent,
  name,
  isRegistered
} = (studentDetail && studentDetail.fields) || {};

console.log(notStudent);
console.log(name);
console.log(isRegistered);
Akshay Bande
  • 2,491
  • 2
  • 12
  • 29
4

You can destructure an empty default object in case your studentDetail.fields doesn't exist:

const { notStudent, name, isRegistered } = studentDetail?.fields ?? {};
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • `const { notStudent, name, isRegistered } = studentDetail?.fields || {};` also work right? Is there any difference between `??` and `||`. – Henok Tesfaye Aug 22 '20 at 14:51
  • 1
    @HenokTesfaye Yes, [there is a difference](https://stackoverflow.com/a/476445/1048572), but if `fields` is always either `null`, `undefined` or an object, it probably doesn't matter. – Bergi Aug 22 '20 at 14:55