Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to destructure a nested object only when it has a value?

Tags:

javascript

  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?

like image 319
Henok Tesfaye Avatar asked Aug 22 '20 14:08

Henok Tesfaye


People also ask

Can you Destructure a nested object?

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.

Can you Destructure array of objects?

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.

Can you Destructure an object?

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.


2 Answers

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);
like image 129
Akshay Bande Avatar answered Oct 23 '22 22:10

Akshay Bande


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

const { notStudent, name, isRegistered } = studentDetail?.fields ?? {};
like image 4
Bergi Avatar answered Oct 23 '22 22:10

Bergi