jonmrich
jonmrich

Reputation: 4333

Create array from ajax call

I'm having trouble getting this into the right format.

I have this:

  $.ajax({
            url: 'att_count_2.php',
            type: 'GET',
            dataType: 'JSON',
            data: allvars[0],
            success: function(data) {

              var export_data = [];
              $('#export').click(function() {
                 $.each(data, function (key, value) {
                 var export_data = value.exuid; 
                 console.log(export_data);
                 //var final_one = export_data.join(",")

                }); 
        });

The console.log give me one line each for the exuids that match my criteria. Like this:

9a2234e4-cfc8-47da-b03a-0ed52e80f0e2  
4d06e206-261b-4774-b553-6785f13cd64e  
1ec1c7ea-85f4-4ba4-ab70-bf1e56cf9bd2  

This works great. However, what I need is this:

[9a2234e4-cfc8-47da-b03a-0ed52e80f0e2,4d06e206-261b-4774-b553-6785f13cd64e,1ec1c7ea-85f4-4ba4-ab70-bf1e56cf9bd2]

If I uncomment out the join statement I have above, it throws an error:

Uncaught TypeError: undefined is not a function

What am I doing wrong here?

Upvotes: 1

Views: 6991

Answers (3)

Guffa
Guffa

Reputation: 700840

You can use the map method to get the property from each item into a new array:

$('#export').click(function() {
  var final_one = $.map(data, function (value) {
    return value.exuid;
  });
  // use final_one
});

Upvotes: 2

Hunter
Hunter

Reputation: 1687

by saying

var export_data = value.exuid;

you're reassigning your export_data array every time. What you want to do is add elements to the export_data array like this:

export_data.push(value.exuid);

Upvotes: 1

Anthony Forloney
Anthony Forloney

Reputation: 91816

The commented out code is trying to invoke a join method on a string object which does not exist (or rather is undefined) hence the error message you are receiving.

When trying to append data onto an array you would need to use push like so,

success: function(data) {
          ...
          var export_data = [];
          $('#export').click(function() {
             $.each(data, function (key, value) {
                export_data.push(value.exuid);
            }); 
    });

Upvotes: 2

Related Questions