Mapping drop-downs based on the length of a JSON array

Looking to generate dropdowns in a React Native mobile application based on the length of values in an API JSON array. Here's an example of the desired output:

eg:- Choice 1 (Label of the Drop Down)
           -Sub Choice 1 . (Value Data)
           -Sub Choice 2 (Value Data)
           -Sub Choice 3 (Value Data)

   Choice 2 (Label of the second Drop Down)
           -Sub Choice 1 . (Value Data)
           -Sub Choice 2 . (Value Data)
           -Sub Choice 3 . (Value Data)

If the API response includes Choice 1 and Choice 2, we would need to generate 2 dropdowns accordingly.

The current code implementation only retrieves the last Choice and Choice Data from the API response array. To achieve the desired functionality, we're using the react-native-material-dropdown library and mapping it according to the length of the JSON array.

 if(responseText.success == true)
    {
      var count = Object.keys(responseText.data).length;  //Getting Array Data Length
      let drop_down_data = [];  //  For Dropdown box
      for(var i=0;i<count;i++){
        // Next Loop for Fetching Choice Items
        var t_count = Object.keys(responseText.data[i].choiceItems).length;
        for(var j=0;j<t_count;j++){

          var Add_On_Name = responseText.data[i].name
          console.log(Add_On_Name)
          this.setState({addOn_name: Add_On_Name});

          this.setState({riceTypeData:responseText.data[i].choiceItems[j].name});
          drop_down_data.push({ value: responseText.data[i].choiceItems[j].name}); 

        }

      }
      this.setState({ drop_down_data , progressDialog:false}); // Set the new state

    }

Answer №1

Hopefully, this information proves useful.

// Starting state set up.
state = {
   selectionOptions: []
};

// Handling the successful API call
if (responseText.success) {
  let all_options = [];
  for (let i = 0; i < responseText.data.length; i++) {
    let individual_options = [];
    for (let j = 0; j < responseText.data[i].choiceItems.length; j++) {
      let option_name = responseText.data[i].choiceItems[j].name;
      let temp_obj = {};
      temp_obj.value = option_name;
      individual_options.push(temp_obj);
    }
    let category_obj = {};
    category_obj.label = responseText.data[i].name;
    category_obj.data = individual_options;
    all_options.push(category_obj);
  }
  this.setState({ selectionOptions: all_options });
}
// Function for displaying multiple dropdowns.
renderDropdowns = () => {
  return this.state.selectionOptions.map(item => {
    return <Dropdown label={item.label} data={item.data} />;
  });
};

render(){
  return <View>{this.renderDropdowns()}</View>;
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Null value arising due to AJAX's asynchronous nature

I am facing an issue with a form that includes a select option displaying various choices. My goal is to retrieve the selected option and display it in a text box. The options are loaded using AJAX from an XML data source. When attempting to grab the sele ...

Exploring the capabilities of Angular through filter functions and ng-bind-html

I created an angular filter called 'strLimit' to restrict the number of characters in a string: mod.filter('strLimit', ['$filter', function ($filter) { return function (input, limit) { if (!input) return; if (input.le ...

Are you looking for methods to alter the elements of a webpage prior to viewing it?

I have created a page with the intention of using it as a tool, but I am facing some challenges due to my limited experience in this field. As a newcomer, I am struggling to achieve certain goals: - My objective is to modify the values of an element on a p ...

Move the menu button to the right of the title slide, beyond the edge of the card

Having an issue with the MuiCardHeader component. <CardHeader disableTypography avatar={renderAvatar()} action={ <IconButton onClick={toggleMenu}> <img src={MoreIcon} alt=""/> </IconButton ...

jQuery: Implementing a function for all elements, including those dynamically loaded through Ajax later on

I have implemented a jQuery function to resize text areas, but I need it to work on all text areas. The function works well for existing text areas: $(document.ready(function(){$("text_area").resizer('250px')}); However, it fails to resize tex ...

Importing JSON data into a Backbone.js model

I'm just starting to explore Backbone. Can you help me figure out what I might be missing in this situation? Below is the model I am using: var Item = Backbone.Model.extend({ url: 'json/item.json', parse: function(response){ retu ...

Encountering 'Element not found' error when automating Flight Booking on MakeMyTrip.com using Selenium WebDriver, specifically while trying to select a flight after conducting a search

Currently in the process of automating the flight booking feature on MakeMyTrip.com using Selenium WebDriver. I have implemented separate classes for Page Object Model (POM) and TestNG. The code successfully automates the process up to the point of clicki ...

Assign a value to an Html.HiddenField without tying it to the model upon form submission

I have two classes, SubsidiaryClient and Client, that are related in a one-to-many manner as depicted below. Currently, I am utilizing MVC 5 for development. In the Create SubsidiaryClient page, to retrieve the ClientID, you need to click on the browse bu ...

Utilizing JQuery and AJAX to upload unprocessed data to a WebAPI

I need help figuring out how to send raw data to a webAPI using JQuery and Ajax. I've been struggling to make the data get transmitted successfully. The API endpoint functions correctly in Postman: https://i.sstatic.net/AX8zL.png Here is my simple J ...

Prevent scrollbar from appearing while splash page loads

Looking for help with a script to create a splash/intro page loader. $(function(){ setTimeout(function() { $('#splash').fadeOut(500); }, 6000); }); The current script hides the intro page after 6 seconds, ...

Allow only specified tags in the react-html-parser white list

Recently, I've been working on adding a comments feature to my projects and have come across an interesting challenge with mentioning users. When creating a link to the user's profile and parsing it using React HTML parser, I realized that there ...

Having trouble with sending an ajax PUT request

UPDATE: The issue of getting an undefined URI was resolved by storing $(this).attr('red') in a variable. However, the 500 Server error persists. UPDATE: For reference, the complete code can be found on GitHub. Just to ensure nothing was overlook ...

What is causing the error message "TypeError: expressJwt is not a function" to appear? Is there a way to resolve it and fix the issue?

Authentication with JWT in Node.js: const expressJwt = require('express-jwt') function setupAuth() { const secret = process.env.SECRET_KEY return expressJwt({ secret, algorithms: ['HS256'] }) } module.expor ...

Avoid using `@typescript-eslint/no-floating-promises` when using a `const` function

Can anyone help me understand why the @typescript-eslint/no-floating-promises rule works with some async functions but not all? To my understanding, these two functions should be equivalent: const getUser = async (userId: string): Promise<User> => ...

Determine the presence of a JSON object within a file using JavaScript

Currently, I am developing a mobile app using react-native and have been facing challenges implementing error checking. To store data retrieved from an API in JSON format, I am employing redux along with thunk. At times, the search results yield a JSON res ...

There appears to be a malfunction in the socket rooms, as they are not operating

I have set up a code where sockets are being sent to the wrong person, and I am unable to figure out why. Whenever I update one user's status, it also updates the other user's status. Snippet of Code io.on('connection', function(socke ...

What is the process to insert a record into a table by triggering an AJAX call upon clicking "save

I'm looking to dynamically update a table with data from a database using AJAX. Specifically, I want the table to reflect any new records added by the user without having to refresh the entire page. Below is my JavaScript code snippet for handling thi ...

Issue arise when utilizing async/await in conjunction with .forEach method

My code is attempting to make a basic request to Redis in order to retrieve all the values (not keys) from my database. However, I am encountering an issue where the tab is being returned before the .forEach function even begins. This is evident because ...

What is the best way to change CSS style for a button when clicked using JavaScript?

Is there a way to switch the background style of a CSS div when clicking the same button? function changeBg() { var divElem = document.getElementById("change-bg"); if (divElem.style.backgroundColor === "yellow") { divElem.style.backgroundColor ...

Include a search button within the search box of the Custom Search Engine

Can anyone help me with adding a search button to my HTML code? I've tried implementing it, but when I try to search something on a website like YouTube, the results show up without displaying my search query. How can I fix this issue and what changes ...