简体   繁体   中英

How can I use jQuery.each() loop on Array of Object

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

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 );
        });

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

data.forEach(function(entry) {
    //Your logic.
});

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM