0

I have the following code where I'm attempting to reference the values of one JSON object with the variables of another:

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]]*/
  }
}

The program correctly orders the columns and I can refer both values from 'ch', but I would like to use the first composites value as a variable reference to the dataset. Having googled the question I followed a couple of recommendations to either use 'this' or 'eval', but neither work. Where am I going wrong?

Ideally, if I could get the commented out code working the log should look like the following:

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

Barmar
  • 741,623
  • 53
  • 500
  • 612
user5072412
  • 187
  • 1
  • 10

1 Answers1

2

Use dataset[l][composites[0]] to get the additional column. See 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]])
  }
}
Barmar
  • 741,623
  • 53
  • 500
  • 612