1

I am receiving a nested object as a response from my API which looks like this:

 myObject = {
   name: 'client name',
   address: {
     building: 'building name',
     block: 'block name',
     street: 'street name'
   }

I am currently destructing it by

  const { name, address: {building, block, street}} = myObject;

The code above works fine when myObject has the address object, but it's possible to get a response with the address object as null. like:

  myObject = {
    name: 'client name',
    address: null,
  }

in that case, I get an error saying: Cannot read property 'building' of null

I have tried destructing like below

const { name, address: {building, block, street} = {}} = myObject;

It only works if I get the address as undefined.

I have accomplished this by destructuring in multiple stages, but would rather do it in a single stage if possible.

4
  • Do you only have to handle null and undefined? Commented Mar 31, 2023 at 3:03
  • This might help stackoverflow.com/questions/56108874/… Commented Mar 31, 2023 at 3:08
  • @Unmitigated only null Commented Mar 31, 2023 at 3:17
  • @CodeThing the mentioned solution only works if I get address as undefined Commented Mar 31, 2023 at 3:19

1 Answer 1

1

You could use a helper function to remove all null entries before destructuring to allow the default value to be used.

const removeNulls = o => Object.fromEntries(Object.entries(o).filter(([k, v]) => v !== null));
let myObject = {
  name: 'client name',
  address: null
};
const { name, address: {building, block, street} = {}} = removeNulls(myObject);
console.log(name, building, block, street);

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer, in my case the address is not present at all.
@WahidullahShadab If it's not present at all, there should be no error. Your original code works fine for that case: jsfiddle.net/uw5hx1eL

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.