TypeError forEach is not a function

I am trying to append array coming from response to some container by javascript forEach function. But getting an error of "response.cat_products.forEach is not a function". What is my wrong?

    return response()->json([
        'status' => true,
        'message' => 'success',
        'cat_products' => $cat_products,
        'cat_count' => $cat_count
    ]);
    if (response.status == true) {
        response.cat_products.forEach(filter); //filter is a function

    }

Upvotes: 0

Views: 736

Answers (1)

Donkarnash
Donkarnash

Reputation: 12835

When a response is returned from Laravel controller like

return response()->json([
    'status' => true,
    'message' => 'success',
    'cat_products' => $cat_products,
    'cat_count' => $cat_count
]);

Then the actual array is available on the javascript side under the response.data key.

Since you are doing loose comparison in the if statement it is being compared with response.status: 200 and not your supplied "status" => true in the json response

if (response.status == true) {
    //response.data should contain the data sent as response from controller
    console.log(response.data); 
    
    //response.cat_products.forEach(filter); //filter is a function

    response.data.cat_products.forEach(filter);  //this should work

}

Upvotes: 1

Related Questions