How to get JSON data with two dynamic variables?

Viewed 24

It's my first post here so if I'm doing something wrong please tell me! I'm still learning React and am working on a project for university.

I'm trying to get the length from my JSON while having two dynamic variables.

my JSON:

"data": { 
  "Java1": {
   "Arrays": {
     "Aufgabe1": {answer:"option1", option1:"A", option2:"B", option3:"C", option4:"D", question:"Foo?"},
     "Aufgabe2": {answer:"option2", option1:"A", option2:"B", option3:"C", option4:"D", question:"bar?"}
     },
   "Schleifen": {
     "Aufgabe1": {answer:"option1", option1:"A", option2:"B", option3:"C", option4:"D", question:"Foo?"},
     "Aufgabe2": {answer:"option2", option1:"A", option2:"B", option3:"C", option4:"D", question:"bar?"}
       }
   },
  "Java2": {
    "Streams": {
      "Aufgabe1": {answer:"option1", option1:"A", option2:"B", option3:"C", option4:"D", question:"Foo?"},
      "Aufgabe2": {answer:"option2", option1:"A", option2:"B", option3:"C", option4:"D", question:"bar?"}
      },
    "Vererbung": {
      "Aufgabe1": {answer:"option1", option1:"A", option2:"B", option3:"C", option4:"D", question:"Foo?"},
      "Aufgabe2": {answer:"option2", option1:"A", option2:"B", option3:"C", option4:"D", question:"bar?"}
      }
    }
}

How I tried getting it:

getData = (e) => {
  const dropdown1 = this.state.selectedOption.value;           // Java1
  const dropdown2 = this.state.selectedOption2.value;          // Arrays
  const temp = Object.keys(this.state.data[dropdown1]).length;
  console.log("dataLength: ", temp);                           // 2
};

This code works, but it only gives me the length of Java1 What I need though, is the length of e.g. Arrays and I have no clue how to get that since Java1 & Arrays are dynamically chosen from two dropdowns.

I have tried some variations like:

const temp = Object.keys(this.state.data[dropdown1].[dropdown2]).length;

or

const temp = Object.keys(this.state.data[dropdown1.[dropdown2]]).length;

but it won't work. (obviously I guess) I cant find any solution or example to this problem (maybe because of language barrier). So if you guys have any idea of how I can get there, I'd really appreciate the help!

0 Answers
Related