Henok Tesfaye
Henok Tesfaye

Reputation: 9570

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

  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?

Upvotes: 5

Views: 102

Answers (2)

Bergi
Bergi

Reputation: 664650

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

const { notStudent, name, isRegistered } = studentDetail?.fields ?? {};

Upvotes: 4

Akshay Bande
Akshay Bande

Reputation: 2587

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);

Upvotes: 6

Related Questions