简体   繁体   English

解构嵌套在数组中的对象

[英]Destructuring a Object nested inside Array

I have the following object structure我有以下对象结构

session: {
  expires: String,
  sessionData: {
    user: Object,
    token: String
  }
}

I want to do the destruct in the same line of code that I define these constants that I get from a hook in react.我想在定义这些常量的同一行代码中进行破坏,这些常量是我从 react 中的钩子获得的。

const [ session, loading ] = useSession();

I am currently doing it this way.我目前正在这样做。 Is there an alternative?有替代方案吗?

 const [ session, loading] = useSession();
 const { user } = session.sessionData;

I want to know if something like this can be done:我想知道这样的事情是否可以做到:

 const [ user: session: {sessionData: user}, loading] = useSession();

您可以像这样解构来设置user变量:

const [{sessionData: { user }}, loading] = useSession();

NOTES:笔记:

1. This code will error if sessionData is null or undefined : 1. 如果sessionDatanullundefined此代码将出错:

const [{sessionData: { user }}, loading] = useSession();

 const useSession = () => [{ expires: new Date(Date.now() + (3600 * 1000 * 24)), sessionData: null }, false]; const [{ sessionData: {user}}, loading] = useSession(); console.log('user:', user, 'loading:', loading);

2. Using the same code, you can't assign an inline default value to fix the TypeError described above.使用相同的代码2,则不能分配一个内联默认值以固定TypeError如上所述。

 const someData = { foo: 'foo', bar: 'bar' }; //assign `baz: 'default'` to avoid `TypeError` if `baz` property does not exist const {foo, bar, baz = 'default'} = someData; console.log(foo, bar, baz); //sadly, this doesnt work here. const useSession = () => [{ expires: new Date(Date.now() + (3600 * 1000 * 24)), sessionData: null }, false]; const [{ sessionData: {user} = {} }, loading] = useSession(); console.log('user:', user, 'loading:', loading);

Maybe I'm missing something but I just can't get it to work using default values.也许我错过了一些东西,但我无法使用默认值让它工作。 The only way I fixed this is getting sessionData first then work on that afterwards while using default values.我解决这个问题的唯一方法是先获取sessionData ,然后在使用默认值的同时处理它。

 const useSession = () => [{ expires: new Date(Date.now() + (3600 * 1000 * 24)), sessionData: null }, false]; //assign {} to `sessionData` if it is undefined const [{expires, sessionData = {} }, loading] = useSession(); console.log(sessionData); //null //above default value will still fail if sessionData is null. // to fix, coalesce to {} const {user, token} = sessionData || {}; console.log(user, token);

3. Be careful with "Gotcha's" 3. 小心“陷阱”

You may have noticed the || {}您可能已经注意到|| {} || {} code in the above code even though we added a default value to sessionData . || {}上面代码中的代码,即使我们向sessionData添加了默认值。 This is because default values only apply to undefined , not null s.这是因为默认值仅适用于undefined ,而不适用于null

On the same note, it is better to add a coalesce on useSession too since your code will break if useSession() returns a null or undefined .同样,最好在useSession上添加合并,因为如果useSession()返回nullundefined您的代码将中断。

 const useSession = () => { return null; }; //assign {} to `sessionData` if it is undefined console.log(useSession()); //null // useSession()[0], aka session is undefined // need to add default since we are destructuring `sessionData` from `session` const [{ sessionData } = {}, loading] = useSession() || []; //// this also works but it assigns `sessionData = {}` //const [{ sessionData = {} } = {}, loading] = useSession() || []; // wont be doing that since we are proving the next point: //above default value will still fail since `sessionData` will be undefined // to fix, coalesce to {} const {user, token} = sessionData || {}; console.log(user, token);

Finally最后

Getting sessionData and/or expires (aka session ) first actually isn't bad at all since you may also want to get the other properties, ie, session.expires , sessionData.token , etc. It also allows you to fix the Gotchas mentioned above.首先获取sessionData和/或expires (又名session )实际上一点也不差,因为您可能还想获取其他属性,即session.expiressessionData.token等。它还允许您修复提到的问题多于。

This awesome article (Object destructuring best practice in Javascript) discusses the above notes in-depth.这篇很棒的文章(Javascript 中的对象解构最佳实践)深入讨论了上述注释。 Take time to read.花时间阅读。

The object structure you provided is not valid.您提供的对象结构无效。 I came to get user and token with following construct:我使用以下构造来获取usertoken

 var a = { session: { expires: '1d', sessionData: { user: 'myUser', token: 'token' } } } var {session: {sessionData: {user, token}, expires}} = a console.log(user, token, expires) // 'myUser token 1d'

For more info, see ES6 deep nested object destructuring有关更多信息,请参阅ES6 深度嵌套对象解构

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

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