Frank Lucas
Frank Lucas

Reputation: 592

jQuery looping over objects of a PHP array

I have a php array that looks like this when I print it out:

Array
(
    [0] => Array
        (
            [title] => Much title
            [end] => Such end
            [start] => Very start
        )

    [1] => Array
        (
            [title] => Much title
            [end] => Such end
            [start] => Very start
        )

)

I've sent this array to my jQuery like so:

var orders = <?php echo json_encode($myArray); ?>;

When I do cosole.log(orders); I get 2 objects obviously.

Output:

enter image description here

Now I want to loop over them I tried like so:

jQuery.each( orders, function( key, value ) {
      console.log( key + ": " + value );
});

This is giving me this output in my console:

0: [object Object]
1: [object Object]

Instead of the title, start and end values of every object.

Anyone has any idea how I can fix this?

Thanks in advance!

Upvotes: 0

Views: 47

Answers (1)

MrCode
MrCode

Reputation: 64536

To iterate the object properties, you need a second loop, because value is the object itself.

jQuery.each( orders, function( key, value ) {
      jQuery.each(value, function(propertyName, propertyValue){
          console.log( propertyName + ": " + propertyValue);
      });
});

Or you can access the properties directly by name:

jQuery.each( orders, function( key, value ) {
    console.log( value.title );
});

Upvotes: 2

Related Questions