简体   繁体   English

分解JS中的对象-嵌套对象

[英]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: {}} 我有一个xhr请求,该请求返回{person: user: {}}

For example: const xhrResponse = {person: user: 'hi'}} 例如: 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} 但是,如果api返回{person: null}该怎么办

My destructuring fails with Cannot match against 'undefined' or 'null'. 我的销毁失败, 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 甚至以另一种方式,更好地使用单词有时是观点的代名词: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) (我假设您根据箭头功能使用es6)

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 编辑:很抱歉,仅适用于未定义的值,但不适用于值为null的情况,因为答案可能对其他读者有用

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 繁琐的解构可能会以不可读的代码结束

So doing progressive destructuring, feels like a better solution to me. 因此,进行渐进式解构对我来说是一个更好的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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