【发布时间】:2022-11-01 19:44:47
【问题描述】:
我有一个这样的 .json 文件:
{ “宽度”:700, “身高”:1382, “数据ID”:{ “id1”:“54321”, “id2”:“12345” } }
我需要动态获取 id1 或 id2 键的值(使用变量)。我使用赛普拉斯函数 cy.read() 并通过使用明确的字符串效果很好:
cy.readFile(pathToConfigFile).then(($file) => {
const id1value = $file.dataID.id1;
});
但是如何将这个表达式包装到包含 id1 的变量中呢? 有一个类似的问题:Dynamically access object property using variable 然而,那里提出的解决方案仅涉及第一级深度。使用方括号,我可以获得以下值:
cy.readFile(pathToConfigFile).then(($file) => {
const customVariable = "dataID";
const id1value = $file[customVariable];
});
但如果它返回 id1value = undefined:
cy.readFile(pathToConfigFile).then(($file) => {
const customVariable = "dataID";
const id1 = "id1";
const id1value = $file[customVariable][id1];
});
【问题讨论】:
-
@GrafiCode 如果
$file[customVariable]未定义,则无法访问其上的属性id1,这将引发错误。 -
我认为 OP 是在说
const id1value = $file[customVariable][id1];是undefined而实际上应该是54321
标签: javascript node.js json typescript cypress