0

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!

6
  • Use console.log( key, value );instead Commented Apr 13, 2016 at 14:21
  • @RejithRKrishnan How can I access the title, start and end values? Commented Apr 13, 2016 at 14:23
  • each docs it's index, value, not key; you need to drill down one further level to get at the content of value Commented Apr 13, 2016 at 14:23
  • 2
    value.title - value.start - value.end Commented Apr 13, 2016 at 14:23
  • @mjr index or key is merely the variable name. Both will work. Commented Apr 13, 2016 at 14:24

1 Answer 1

2

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 );
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.