Reputation: 6701
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);
Upvotes: 3
Views: 666
Reputation: 29092
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);
Upvotes: 3
Reputation: 4080
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
So doing progressive destructuring, feels like a better solution to me.
Upvotes: 2
Reputation: 3342
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
Upvotes: 2