0

Very new to jQuery, don't fully understand the differences between objects and arrays so I apologize if my terminolog is incorrect - please correct me!

I have a successful ajax return array from PHP:

$.ajax({
    url: "......",
    dataType: "json",
    type: "GET",
    data: {
        start_date: start,
        end_date: end
    },
    success: function (res) {
        $.each(res, function( key, value ){
            $('#FoundEvents').append('<option value="'+ key +'">'+ value +'</option>');
        });
    }
});

This gives me [object Object] in each option tag. To ask the obvious, I'm dealing with an object not an array? All the data is present, I just can't find the correct syntax to access it. How do I iterate the array data from this point?

If I understand my console readout correctly, there are 10 'objects' then inside each object are several 'keys:values'.

Thanks for your help!

Update

PHP Array is structured like so: $arr = array(1 => array(key=>value), 2 => array(key=>value) ...)

I'm trying to access values.

Update 2

Here's my new code:

 $.each(res, function(index, item){
    $.each(item, function(key, value){
        if(key == "event_title")
        {
            Events.push({"event_title":value});
        }
    });
});
$.each(Events, function(index, value){
    $('#FoundEvents').append('<option value="'+ index +'">'+ Events.value +'</option>');
});

But somehow I still have objects in my array? I don't understand why. I assume 'value' itself is the object... which I don't mind, but need to know how to pluck the data out.

SeinopSys
  • 8,787
  • 10
  • 62
  • 110
Joe
  • 427
  • 1
  • 6
  • 16

3 Answers3

0

There are plenty of places that will help explain the difference between an Array and an Object. For short, in JavaScript an Array is a type of Object. It inherits all of the properties of Object, but has additional properties and methods, such as numerical indexing and pushing/popping.

When you say that in your console there are 10 Objects, are you referring to the contents of res in your success handler? It sounds like you might have a nested Object for each element in res. Without knowing how the returned JSON data is structured, it's a little tricky to diagnose the problem.

Can you post the output of doing a console.log(res); in your handler?

Update

Ah, so you do have nested Objects coming as the response. You may need to restructure that PHP array like this:

$arr = array(1 => array(key=>"something", value=>"something's value"), 2 => array(key=>"something else", value=>"something else's value") ...)

Then, in your success handler's each function, you can do:

$.each(res, function( index, item ){
  var key = item.key,
      val = item.value;

  $('#FoundEvents').append('<option value="'+ key +'">'+ value +'</option>');
});

Update 2

If you really can't change the way the PHP is sending the response, you'll probably need to do something like this. But, as mentioned, this seems like overkill since the Objects in the res Array are only going to have a single key/value pair.

$(document).ready(function () {
    $.each(res, function(index, item) {
      $.each(item, function(key, value) {
        // do something with key and value
      });
    });
});
Community
  • 1
  • 1
benjarwar
  • 1,794
  • 1
  • 13
  • 28
  • That is correct, there is a nested object in each element of res: Array [ Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, 1 more… ] – Joe Aug 03 '15 at 01:50
  • Right. But you don't have an (easy) way of accessing the key for each nested Object, since each one is structured like {key: value}. You could perform a nested $.each for each item in the Array ```res```, but that seems like overkill since there's only a single node in each Object. Better, perhaps, to simply restructure response. – benjarwar Aug 03 '15 at 01:55
  • I can definitely do that, however it would create performance issues later on in the application - I need to keep all the data sent by php. Even splicing out the data in a couple different jQuery arrays would be fine. Anyway you could provide a solution for the jQuery side as well, I just need to see what the syntax might look like? – Joe Aug 03 '15 at 02:12
  • Updated with an example of how you could do this with a nested ```$.each```, but I wouldn't recommend it :) – benjarwar Aug 03 '15 at 02:24
  • So I used your nested loop and it seems to work, except 'value' is still showing up as object.... I still can't get the value itself. Any suggestions? – Joe Aug 03 '15 at 15:11
  • As requested earlier, can you post the output of doing console.log(res); in your handler? Would like to see exactly how the JSON response is formatted. – benjarwar Aug 03 '15 at 16:07
0

The data you're iterating may have the key field, but jQuery won't unpack it for you. That is why you're getting the [object Object] text instead of the actual value. You should transform the data like this before returning it to the webpage:

[{'key1': 'val1'}, {'key2': 'val2'}]

to

{'key1': 'val1', 'key2': 'val2'}

But if you care about order (object traversal order is arbitrary), you can instead make it like this:

[{key: 'key1', value: 'val1'}, {key: 'key2', value: 'val2'}]

and then access the data like this in your array:

 $('#FoundEvents').append('<option value="'+ obj.key +'">'+ obj.value +'</option>');
Anonymous
  • 11,740
  • 3
  • 40
  • 50
0

You are almost there. The second paramter in the callback function is an array or an object, the first is the array index of object property. You must use the index/property to get at the value.

try the following:

success: function (res) {
    $.each(res, function( key, value ){
        $('#FoundEvents').append('<option value="'+ key +'">'+ value[key] +'</option>');
    });
}

Take note of my change which is the text within the option tag.

You may also consider logging out the object to the console so you can inspect the structure, see below:

success: function (res) {
    $.each(res, function( key, value ){
        //The output can be found in developer console which is found in any modern browser.
        console.log(value);
        $('#FoundEvents').append('<option value="'+ key +'">'+ value[key] +'</option>');
    });
}
dlporter98
  • 1,590
  • 1
  • 12
  • 18