javascript - 奇怪的解构赋值,给出未定义
问题描述
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
特定位置失败const
securityContext
我从未见过这样的模式,我想知道是否有办法简化它。
解决方案
这是一种复杂的解构赋值
您可能熟悉这种更简单的类型。
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
直接获取,然后提取元素securityType
和apiKey
.
也许作者试图避免securityContext
获得除这两个之外的任何其他部分?这就是为什么他们选择先提取它们,然后重新组装一个securityContext
只有所需物品的新产品。
如何重写它以使其更易于理解
const apiKey = securityContextConfigurations.apiKey
const securityType = securityContextConfigurations.securityType
const securityContext = { apiKey, securityType };
推荐阅读
- c - C 程序计算字符串中的用户输入并将总成本打印到 int 中
- html - CSS Grid 中的行高扩展
- c++ - 如何在 if 语句中设置字符串值?(C++)
- keras - Keras 中 LSTM 的多变量输出的输出序列
- r - 如何在 r 中找到我的 PCA 图中的数据点?
- google-cloud-platform - 谷歌计算引擎 - 没有资源
- swift - 获取位置点和标题并在 mapkit 视图上显示
- c++ - 从另一个线程关闭和打开 QSerialPort
- azure - 如何为多租户 Azure 应用创建应用后台作业
- context-free-grammar - 语言 L = {a^(n)b^(m)c^(k): m = |i - k|} 的上下文无关文法