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?
JavaScript destructuring, nested and otherwise, is a nice shorthand to allow us to quickly define variables from values in a collection, object, or array. We can use it with rest syntax to assign remaining elements a variable. We can rename the elements that we pull out to a variable name of our choosing.
Array DestructuringValues in arrays are destructured based on their index . The variable can be named anything you want, but the variable name associated with the index is how it is assigned. We can also assign values to variables that are already declared.
Destructuring is a JavaScript expression that allows us to extract data from arrays, objects, and maps and set them into new, distinct variables. Destructuring allows us to extract multiple properties, or items, from an array at a time.
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);
You can destructure an empty default object in case your studentDetail.fields
doesn't exist:
const { notStudent, name, isRegistered } = studentDetail?.fields ?? {};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With