简体   繁体   中英

create array from response data using javascript

function LoadSuppliers() {  
    $.ajax({
        type: 'GET',
        url: '/supplier/getSupplier',
        success: function(response) {
          console.log(response);
        
          var result = response.data.result;
          console.log(result);

        
        }, error: function(data) {
          console.log('something went wrong!');
        }
    });

This is my loadSupplier function and I want to get these response data into a array and set to input field for autocomplete.. How can I Make a array here..

you can JSON.parse() to convert json response to JS object. then convert JS object to array

var yourArray = $.map(JSON.parse(response), function(value, index){
        return [value];
    });

You need to add a parameter "dataType".

dataType: "JSON",

So in case that you are getting JSON response, you can do the following as;

function LoadSuppliers() {  
    $.ajax({
        type: 'GET',
        url: '/supplier/getSupplier',
        success: function(response) {
          var result = JSON.Parse(response);
          var result_array = [];
            for (const key in result) {
               result_array.push(result[key]); /// array with no key
                 //if you want to get JSON array,
                 let temp = {};
                 if (!result_array.hasOwnProperty(key)) {
                     temp[key] = [];
                  }
                 temp[key].push(result[key]); /// JSON Array
                 result_array.push(temp);
             }
          
          console.log(result_array);
        
        }, error: function(data) {
          console.log('something went wrong!');
        }
    });

Hope this could help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM