【问题标题】:Convert string value to variable reference in javascript在javascript中将字符串值转换为变量引用
【发布时间】:2020-02-10 23:17:43
【问题描述】:

我有以下代码,我试图用另一个 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][position]
  • 不完全一样,比如dataset[l].VAR1, dataset[l].VAR4, dataset[l].VAR2

标签: javascript arrays json reference


【解决方案1】:

使用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]])
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-02
    • 1970-01-01
    • 2020-02-13
    • 2017-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多