javascript - 将字符串值转换为 JavaScript 中的变量引用

标签 javascript arrays json reference

我有以下代码,我尝试使用另一个 JSON 对象的变量引用一个 JSON 对象的值:

const ch = {
  "columns": {
    "COL1": {
      "position": 1,
      "composites": ["VAR1", "VAR3"]
    },
    "COL2": {
      "position": 3,
      "composites": ["VAR2"]
    },
    "COL3": {
      "position": 2,
      "composites": ["VAR4"]
    }
  }
}

const dataset = [{
    "VAR1": "alpha",
    "VAR2": 2,
    "VAR3": "1015",
    "VAR4": "z",
  },
  {
    "VAR1": "beta",
    "VAR2": 701,
    "VAR3": "1023",
    "VAR4": "z"
  }
]

for (let l = 0; l < dataset.length; l++) {
  for (const {
      position,
      composites
    } of Object.values(ch.columns).sort((a, b) => a.position - b.position)) {
    console.log(position, composites[0], dataset[l].VAR1)
    /* eval[dataset[l].composites[0]], this[dataset[l].composites[0]]*/
  }
}

程序正确地对列进行排序,我可以引用“ch”中的两个值,但我想使用第一个复合值作为对数据集的变量引用。在谷歌上搜索了这个问题后,我遵循了一些使用“this”或“eval”的建议,但都不起作用。我哪里出错了?

理想情况下,如果我能让注释掉的代码正常工作,日志应该如下所示:

1 VAR1 alpha alpha 
2 VAR4 alpha z
3 VAR2 alpha 2
1 VAR1 beta  beta
2 VAR4 beta  z
3 VAR2 beta  701

最佳答案

使用dataset[l][composites[0]]获取附加列。请参阅Dynamically access object property using variable

const ch = {
  "columns": {
    "COL1": {
      "position": 1,
      "composites": ["VAR1", "VAR3"]
    },
    "COL2": {
      "position": 3,
      "composites": ["VAR2"]
    },
    "COL3": {
      "position": 2,
      "composites": ["VAR4"]
    }
  }
}

const dataset = [{
    "VAR1": "alpha",
    "VAR2": 2,
    "VAR3": "1015",
    "VAR4": "z",
  },
  {
    "VAR1": "beta",
    "VAR2": 701,
    "VAR3": "1023",
    "VAR4": "z"
  }
]

for (let l = 0; l < dataset.length; l++) {
  for (const {
      position,
      composites
    } of Object.values(ch.columns).sort((a, b) => a.position - b.position)) {
    console.log(position, composites[0], dataset[l].VAR1, dataset[l][composites[0]])
  }
}

关于javascript - 将字符串值转换为 JavaScript 中的变量引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60159885/

相关文章:

javascript - 选择选项时 react native 自动完成输入列表未关闭

javascript - 在 react-native 中调用其他组件的函数

Javascript:大括号中数组后的括号

arrays - 相关值网络 - 如何只重新计算一次它们?

java - 当我尝试解析 JSON 字符串时收到意外的内部错误

java - 使用 gson TypeAdapter 将嵌套的 JSON 转换为嵌套的 Java 对象

android - 如何从此 json 对象中提取字符串数组?

javascript - 单击与单击传入元素

javascript - React Native - 不变违规 : Element type is invalid: expected string but got: undefiend

javascript - 如何更改 javascript 中的\"back to "?