首页 > 解决方案 > 奇怪的解构赋值,给出未定义

问题描述


const apiConfig = JSON.parse(process.env.apiConfig);
const securityContextConfigurations = _.get(
  apiConfig,
  'agpAPIs',
  {});

/// what is going here?

const {
  securityContext : { apiKey, securityType }
} = securityContextConfigurations;

/// end what is going on here?
/// securityContext always comes back as undefined even though there is data in the securityContextConfigurations object

const securityContext = { apiKey, securityType };
const { serviceContext } = apiConfig;
serviceContext.refID = v5(serviceContext.refID, v1());
return Promise.resolve({ securityContext, serviceContext });

securityContextConfigurations是一个对象,我正在寻找的键值对位于对象中,但我的代码总是在我试图为其创建对象的securityContextConfigurations特定位置失败constsecurityContext

我从未见过这样的模式,我想知道是否有办法简化它。

标签: javascripttypescriptexpresslodash

解决方案


这是一种复杂的解构赋值

您可能熟悉这种更简单的类型。

const a={b:3, c:"hello"}

const {b, c} = a

console.log("b is ",b)
console.log("c is ",c)

在这里,他们只是在做一个额外的水平。

const securityContextConfigurations = {
  securityContext: {
    apiKey: "hello",
    securityType: "high"
  }
}

const {
  securityContext: {
    apiKey,   
    securityType
  }
} = securityContextConfigurations;

// The innermost items are extracted as variables

console.log("apiKey is", apiKey)
console.log("securityType is", securityType)
// However "securityContext" is not extracted as a variable

请记住,在 JS 中 {a, b} 是 {a:a, b:b} 的简写。为了探索发生了什么,我们可以在“:”的两侧放置不同的变量名。

const securityContextConfigurations = {
  securityContext: {
    apiKey: "hello",
    securityType: "high"
  }
}

const {
  securityContext: {
    apiKey:x,   
    securityType:y
  }
} = securityContextConfigurations;

// The destination variable name on the *right hand side* of the ":". The variable name on the left of the ":" is only to tell JS which element of the source to extract.  

console.log("x is", x)
console.log("y is", y)

// apiKey, securityType and securityContext are not extracted as variabels. 

如果有什么安慰的话,我用 JS 编码已经有十多年了,而且我以前也从未见过它。8-)

程序员可能在做什么

出于他们最熟悉的原因,他们想提取较小的元素,然后将它们重新组合成更大的对象securityContext

因此,您突出显示的代码 apiKey获得and securityType

之后的行重建一个securityContext包含这些元素的新对象。

通常你和我可能会securityContext直接获取,然后提取元素securityTypeapiKey.

也许作者试图避免securityContext获得除这两个之外的任何其他部分?这就是为什么他们选择先提取它们,然后重新组装一个securityContext只有所需物品的新产品。

如何重写它以使其更易于理解

const apiKey = securityContextConfigurations.apiKey
const securityType = securityContextConfigurations.securityType
const securityContext = { apiKey, securityType };


推荐阅读