解构嵌套在数组中的对象

Destructuring a Object nested inside Array

我有以下对象结构

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

我想在我定义这些常量的同一行代码中进行破坏,这些常量是我从反应中的钩子中获得的。

const [ session, loading ] = useSession();

我目前就是这样做的。有替代方案吗?

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

我想知道是否可以做这样的事情:

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

您提供的对象结构无效。我用以下结构来获得 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'

有关详细信息,请参阅

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

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

备注:

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。使用相同的代码,您无法分配内联默认值来修复上述 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);

也许我遗漏了一些东西,但我无法使用默认值让它工作。我修复此问题的唯一方法是先获取 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。小心“陷阱”

您可能已经注意到上面代码中的 || {} 代码,尽管我们为 sessionData 添加了默认值。这是因为默认值仅适用于 undefined,不适用于 null

同样,最好在 useSession 上添加一个合并,因为如果 useSession() returns a null 或 [=16,您的代码将中断=].

const useSession = () => { return null; };

//assign {} to `sessionData` if it is undefined
console.log(useSession()); //null

// useSession()[0], a.k.a. 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);

终于

首先获得 sessionData and/or expires (a.k.a session) 实际上一点也不差,因为您可能还想获得另一个属性,即 session.expiressessionData.token 等。它还允许您解决上述问题。

本文 awesome article (Object destructuring best practice in Javascript) 深入讨论了上述注释。花时间阅读。