1

I have a .json file like this:

{ "width": 700, "height": 1382, "dataID": { "id1": "54321", "id2": "12345" } }

I need to get value of id1 or id2 keys dynamically (using a variable). I use Cypress function cy.read() and by using definite strings it works good:

cy.readFile(pathToConfigFile).then(($file) => {
const id1value = $file.dataID.id1;
});

But how to wrap this expression into variable containing id1? There is a similar question : Dynamically access object property using variable However the solution proposed there refers only to the first level of depth. With square brackets I can get the following values:

cy.readFile(pathToConfigFile).then(($file) => {
const customVariable = "dataID";
const id1value = $file[customVariable];
});
        

But in case of it returns id1value = undefined:

cy.readFile(pathToConfigFile).then(($file) => {
const customVariable = "dataID";
const id1 = "id1";
const id1value = $file[customVariable][id1];
});
Valeriia
  • 586
  • 2
  • 4
  • 21
  • @GrafiCode if `$file[customVariable]` is undefined you cannot access property `id1` on it and this will throw an error. – Dakeyras Nov 01 '22 at 11:48
  • I think OP is saying this `const id1value = $file[customVariable][id1];` is `undefined` when it actually should be `54321` code seems to work (ignoring Cypress) https://jsfiddle.net/nqy1r2s9/ – GrafiCode Nov 01 '22 at 11:49

1 Answers1

1

You will need to check the value of the variable after the first check so you know whether you can read the second-level value.

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

Instead of undefined you can return some default value if you prefer.

There are also packages which can be used to do this automatically for you, such as lodash's _.get() method.

Dakeyras
  • 1,829
  • 5
  • 26
  • 33