【问题标题】:Get JSON value by using variables on the 2nd level of depth通过使用第二级深度的变量获取 JSON 值
【发布时间】: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


【解决方案1】:

您需要在第一次检查后检查变量的值,以便知道是否可以读取第二级值。

cy.readFile(pathToConfigFile).then(($file) => {
  const customVariable = "dataID";
  const id1 = "id1";
  const idValues = $file[customVariable];
  return idValues ? idValues[id1] : undefined;
});

如果您愿意,您可以返回一些默认值,而不是 undefined

还有一些软件包可用于自动为您执行此操作,例如 lodash's _.get() method

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-26
    • 2022-10-16
    相关资源
    最近更新 更多