Destructuring Object in JS - Nested Object

Viewed 622

How can I handle destructuring a nested object that might have an undefined internal object?

For example.

I have a xhr req that returns {person: user: {}}

For example: const xhrResponse = {person: user: 'hi'}}

I am only interested in the user portion so I destruct.

const {person: {user}} = xhrResponse

console.log(user) => 'hi'

However what if the api returns {person: null}

My destructuring fails with Cannot match against 'undefined' or 'null'.

I have a solution but I feel like there might be a more elegant solution.

Solution

const handleResponse(res) => res.person ? res : {person: user: {}}

Is there a better way to handle this? Or even another way, the use of the word better is sometimes synonymous with opinion :D

More Complete Use Case:

$q.all([somePromise, someOtherPromise, getPersonPromise])
  .then(promises => [vm.promise1, vm.promise2, {person: {user: vm.user}] = promises);
3 Answers
Related