简体   繁体   中英

Destructuring Object in JS - Nested Object

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

You can add default values for nested stuff as well:

const handleResponse = ({ person: { user = {}} = {}} = {}) => {
  console.log(user);
}

handleResponse({});

(i'm assuming you using es6 based on your arrow functions)

edit: sry, only works with undefined values, but not if a value is null will leave the answer in here anyway as it might be useful to other readers

Could you just use this?

const {user} = xhrResponse.person || {};

For the updated use case I wonder whether this would be viable?

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

Personally, I like to see clearly the parameters my function is receiving.

I will go with this solution:

const handleResponse = (response) => {
  const { person: { user } = {} } = response || {};

  // since user is the value to be used you don't need to set a default unless you need it
  if (user) // do your stuff here
}

Doing tedious destructuring can end in unreadable code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM