I want to create a form of sorts that displays questions that the user can navigate to access other answers/questions. Depending on the answer, it will display another question/answer.
Let’s say I have:
var json =
{
"Did you restart the computer?": [
{
"Yes": [
{
"Is the software running?": [
{
"Yes": "Cannot help",
"No": "Open it"
}
]
}
],
"No": "Please restart it"
}
]
}
Is there a data structure that lets me access the option Yes/No by index? For example, doing json[0][0] or json[0][1].
Let’s say the user selects Yes on the first set of options. I know I can access the keys by doing
Object.keys(json["Did you restart the computer?"][0]["Yes"][0])
>> ['Is the software running?']
And if the user selects Yes again, I know I can access the keys by doing
Object.keys(json["Did you restart the computer?"][0]["Yes"][0]["Is the software connected to the server?"][0])
>> (2) ['Yes', 'No']
But this seems somehow cumbersome. Is there a better way to do this so I can access keys/values using indexes (ex. json[0][0][1])?
2
Answers
I should preface this by saying, I don’t think it is a very good question for StackOverflow (it is a good question, but to answer it you may get very opinion based responses — which StackOverflow is often not about).
You can access objects by keys, if you want to use indexes the simplest thing is to use an array, and also remove the text element from your data structure. It could be that you use a structure more like this:
Now
options[0].yes.options[0].yes.options[0].text
isCan't help
.If you restructure the JSON to use arrays, you can simplify the tests