TV Nath TV Nath - 1 year ago 152
React JSX Question

React JS - Parse a complex Json structure and Populate in a dropdown list

I get a backend data structure as following.

"courseDetails" :
[{"departmentId" : 105654,
"courses" :
[{"stream" : "science","courseIds" : ["104","105","106"]},
{"stream" : "art","courseIds" : ["102", "103"]}]
{"departmentId" : 105655,
"courses" :
[{"stream" : "commerce","courseIds" : ["101", "100"]}]

In the UI, I have three dropdown lists.

Department ID | Stream | Course ID

First Department ID dropdown list should be populated with departmentIDs 105654 and 105655. When department id 105654 is selected, Stream dropdown list should be populated as science and art. When science is selected from this second dropdown list, course ids should be populated in third dropdown list as 104, 105, 106.

The json data structure above is to have all data at once so that I don't have to make backend call each time a dropdown option is selected.

How can I achieve this using react js? I am new to it.

Answer Source

Assuming that you receive data in data and your dropdown components each accept an array that must be inserted in their respective dropdown menus, you get the arrays like this:

const Department = => obj.departmentId);

Now assuming you have some departmentId selected, you can do:

const streams = data.courseDetails.filter(x => x.departmentId === departmentId)[0] =>

Now assuming you have the stream stored in streamId, you can do:

const courseIds = data.courseDetails.filter(x => x.departmentId === departmentId)[0].courses.filter(x => === streamId)[0].courseIds;

You should store each array in a state and pass on that state as a prop to the corresponding dropdown components.