简体   繁体   English

如何在对象数组上使用 jQuery.each() 循环

[英]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()?我有这个对象数组,如何使用 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类型错误:无效的“in”操作数 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.我建议你改用 forEach。 jQuery.each method has another goal. jQuery.each 方法有另一个目标。

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.您的 jQuery.each 语法是正确的,但正如 Karl-André Gagnon 所提到的,这是 PHP 数组的输出。

Pass your array through json_encode before sending it to the front-end.在将数组发送到前端之前通过json_encode传递数组。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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