Guide on converting a complex nested json into the jquery autocomplete format

How can I properly format a complex nested JSON for use with jQuery autocomplete? I have been attempting to map my custom JSON data to fit the required jQuery autocomplete format of label and value, but unfortunately, my list is returning as 'undefined'. Here is the setup I am working with:

JSON:

{"data":[{"DT_RowId":"row_A6J851","accounts":{"code":"A6J851","name":"Peter Jackson"}},{"DT_RowId":"row_1D01Q14","accounts":{"code":"1D01Q14","name":"Earl Bundy"}}]}

Javascript:

$('#input-search').autocomplete({
source: function ( request, response ) {
  $.ajax({
    type: 'GET',
    url: '/source.php', 
    dataType: "json",
    success: function( data ) {
        response( $.map( data.data.accounts, function( value, key ) {
            return {
              label: value.name,
              value: value.name,
              id: value.code
            }
        }));
      }
    });
},  
create: function() {            
    $(this).data('ui-autocomplete')._renderItem  = function (ul, item) {
        return $( "<li></li>" )
            .append( "<a>" + item.label + "</a>" )
            .appendTo( ul );
    };         
}       
});

Answer №1

It seems like in the given example data, you are not properly traversing through the nested accounts array but rather the main data array. To correct this issue, consider implementing the following code:

$('#input-search').autocomplete({
  source: function ( request, response ) {
    $.ajax({
      type: 'GET',
      url: '/update-source.php', 
     dataType: "json",
     success: function( info ) {
       var results = [];
       $.each(info.data, function(d){
         var mapped = $.map(d.accounts, function( value, key ) {
          return {
            label: value.name,
            value: value.name,
            id: value.code
           };
          })
         results = results.concat(mapped);       
         });
         response(results);
        }
      });
 },  
 create: function() {            
    $(this).data('ui-autocomplete')._renderItem  = function (ul, item)     {
         return $( "<li>" )
            .append( "<span>" + item.label + "</span>" )
            .appendTo( ul );
  };         
 }       
});

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

Encountering a type conversion error when trying to parse JSON data in C

When attempting to populate a vector of json data type with json objects, I encountered an error when loading this vector into a json response. The following method was attempted to push json objects into the vector of json data type: std::vector<json_ ...

What is the best way to dynamically add the 'required' attribute to an input field?

My responsibility was to dynamically add required fields to all elements on each state that the user selected as required. In my database, I have a table containing the input ID (each input has a unique ID) and a boolean field indicating whether or not a r ...

The attempt to run 'readAsBinaryString' on 'FileReader' was unsuccessful. The first parameter is not the expected type 'Blob'

I am currently working on parsing an xls file. You can find the file by clicking on the following link: However, I am encountering an error that says: 'Failed to execute 'readAsBinaryString' on 'FileReader': parameter 1 is not of ...

Issue with MUI-table: The alternate rows in the MUI table component are not displaying different colors as intended

Struggling to apply different colors for alternate table rows function Row(props) { const { row } = props; const StyledTableRow = styled(TableRow)(({ theme }) => ({ '&:nth-of-type(odd)': { backgroundColor: "green", ...

Issue with Express - Session not persisting across consecutive SSE requests

Currently, I am delving into Server-sent Events using Node.js and Express. I have successfully set up request handling and stream writing, but I am facing challenges with session management. The session does not persist between subsequent calls. Snippet o ...

I am encountering the org.json.JSONException error message stating that there is no value for a specific item in my JSON array

Despite having "feels_like" in my JSON array, the error log is indicating that it is not present. CODE: protected void onPostExecute(String s) { super.onPostExecute(s); try { JSONObject jsonObject = new JSONObject(s); ...

Failed Axios POST request on iOS devices

Attempting a straightforward ajax POST from domain1 to domain2 using Axios. This involves a cross-domain simple POST without requiring a PREFLIGHT (OPTIONS) call. The response returned by the application is a basic JSON string. This process functions smoo ...

Utilizing turbolinks enables the page to be reloaded upon form submission

Currently, I have implemented turbolinks in my Rails application. However, every time I submit a form, the page reloads and the form is submitted. Is there a way to prevent the page from reloading and also submit the form seamlessly? ...

Trigger oncopy on the body excluding specific class

Is there a way to execute a function on document.body.oncopy but exclude a certain class (defined for div elements) from this function call? I want to avoid calling the function on specific classes, is there a method to achieve this? ...

Transferring information through AJAX to the current page using a foreach loop in Laravel 5

As a newcomer to ajax and laravel 5, I am eager to learn how to pass data with ajax to populate a foreach loop in laravel 5 on the same page. <div class="row" style="margin:3% 0px 0px 0px"> @foreach($warung_has_kategoriwarungs['i want pass ...

What is the most effective way to retrieve JSON data from a custom SQL query?

I'm working with this PHP code snippet: <?php $servername = "host"; $username = "user"; $password = "passw"; $dbname = "dbname"; $conn3 = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn3->setAttribute(PDO::ATTR_E ...

Gamepad interference causing obstruction of `requestAnimationFrame()`

I'm currently working with the Gamepad API and finding it a bit challenging due to its limited development. It appears that there is no "gamepadbuttondown" event available, which can be frustrating. I came across a library called 'awesome-react-g ...

Ways to display spinner animations during image loading on Next.js?

Currently, I am attempting to implement a spinner display while images are loading on a Next.js website. To achieve this, I am utilizing the NextUI UI library. My website features several cards, and my goal is to showcase a spinner during the image loadin ...

How do browsers typically prioritize loading files into the cache?

Out of curiosity, I wonder if the categorization is determined by file names or byte code? It's possible that it varies across different browsers. Thank you! ...

Troubleshooting: Magento checkout page keeps scrolling to the top

We are experiencing an issue where, during the one page checkout process, the next step is not automatically scrolling to the top of the page when it loads. After a user fills out all their billing information and clicks continue, the next step appears ha ...

Preserving Scroll Location Through Back Button Usage and Ajax Manipulation of the Document Object Model

Currently, I am incorporating a feature where results are loaded in using ajax with an infinite scroll. However, there is an issue when a user clicks on an item in the list and navigates away from the page - upon returning by clicking the back button, they ...

Display or conceal a div based on checkbox selection

I am trying to implement functionality to show/hide a div when a single checkbox is selected. Currently, it works with "Select all" but I am struggling to make it work with a single checkbox. Below is the code for "Select All": JS: <script language=&a ...

Obtaining targeted information from JSON using JavaScript

Extracting specific data from a JSON object can be challenging, especially if you are new to JavaScript. Below is an example of JSON data containing various fields: {"Date":"2021-01-31........ to ....10.9,"windDir":"SSE"} ...

The functionality of Material Autocomplete is not compatible with InputProps

I am experiencing an issue with customizing the border of my TextField within my Autocomplete component. When I include the InputProps prop, the Autocomplete stops rendering Chips <Autocomplete multiple freeSolo options={options} render ...

Significant delay in processing second jQuery Ajax call

Attempting a simple Ajax call with page content refresh using the following code snippet: $("a.ajaxify-watched").bind("click", function(event) { $item = $(this); $.ajax({ url: $(this).attr("href"), global: false, type: "G ...