1

I have this array of object, how can I loop through it using jQuery.each()?

Array
(
 [0] => stdClass Object
 (
 [id] => 1
 [parent_cat_id] => 1
 [child_cat_name] => Java
 [status] => 1
 [date] => 2016年09月11日 01:26:00
 )
 [1] => stdClass Object
 (
 [id] => 2
 [parent_cat_id] => 1
 [child_cat_name] => JavaScript
 [status] => 1
 [date] => 2016年09月11日 01:26:00
 )
 [2] => stdClass Object
 (
 [id] => 3
 [parent_cat_id] => 1
 [child_cat_name] => HTML
 [status] => 1
 [date] => 2016年09月11日 01:26:00
 )
 [3] => stdClass Object
 (
 [id] => 4
 [parent_cat_id] => 1
 [child_cat_name] => PHP
 [status] => 1
 [date] => 2016年09月11日 01:26:00
 )
 [4] => stdClass Object
 (
 [id] => 5
 [parent_cat_id] => 1
 [child_cat_name] => Python
 [status] => 1
 [date] => 2016年09月11日 01:26:00
 )
 [5] => stdClass Object
 (
 [id] => 6
 [parent_cat_id] => 1
 [child_cat_name] => Ruby
 [status] => 1
 [date] => 2016年09月11日 01:26:00
 )
)

I am trying to use this -

$.each( data, function( key, value ) {
 console.log( value );
});

Which giving me following error -

TypeError: invalid 'in' operand e

asked Sep 14, 2016 at 18:30
3
  • 2
    You show us the dump of a PHP object, can you show us the log of the JS one? Commented Sep 14, 2016 at 18:34
  • This is what I get if i do console.log(data) Commented Sep 14, 2016 at 19:24
  • @Simon then you are not returning json to the client. Commented Sep 14, 2016 at 19:42

3 Answers 3

9

Your array has strange formatting. See this example:

 var data = [ 
 {text: "hello"},
 {text: "good bye"},
 {text: "Hello again"} 
 ]
 $.each( data, function( key, value ) {
 console.log( value.text );
 });
answered Sep 14, 2016 at 18:41
Sign up to request clarification or add additional context in comments.

Comments

0

I suggested you to use forEach instead. jQuery.each method has another goal.

data.forEach(function(entry) {
 //Your logic.
});
answered Sep 14, 2016 at 18:40

Comments

0

Your jQuery.each syntax is correct, but As Karl-André Gagnon mentioned, that is the output of a PHP array.

Pass your array through json_encode before sending it to the front-end.

http://php.net/manual/en/function.json-encode.php

answered Sep 14, 2016 at 18:44

4 Comments

Yes I know I can pass is it using json_encode, but I want to keep my data like this so it is suitable for normal php loops.
@Simon you can't do both.
@Simon, what I mean is pass it through json_encode as you're passing it to the client-side. You don't have to convert it permanently.
Thank you guys, I will think about it.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.