How to get the values of an object from an array returned from Laravel?

Asked

Viewed 30 times

0

I need to get the values an array that is being returned from the Laravel, but I’m not getting to understand how to do this.

Laravel:

if ($request->ajax()) {
                return response()->json([
                    $prod->unique()
                ]);
            }

Array:

[
   [
      {
         "id":3,
         "nome":"Cerveja HEINEKEN Garrafa 330ml",
         "preco":"4,80",
         "tamanho":"330ml",
         "desc":null,
         "imagem":"0310412021060360b848319b870.jpg",
         "qunt":"37",
         "categoria":"1",
         "created_at":"2021-06-03 03:10:41",
         "updated_at":"2021-06-17 02:33:05"
      }
   ]
]

I want to have access to each of the values through Javascript.

Ex:

<script>

   ....

    success: function(data) {

      alert(***Queria o preco aqui***);

    },

</script>

1 answer

0


You have to run each array of the returned json. You can use the function $.each jQuery to interact with your array/object:

success: function(data) {
    $.each(data[0], function(i, produto){
        alert(produto['preco']);
    });
},

Or, if you return more data in this array in the future, you can also better organize the data returned by Laravel:

if ($request->ajax()) {
    return response()->json([
        'produtos' => $prod->unique()
    ]);
}

JS

success: function(data) {
    $.each(data.produtos, function(i, produto){
        alert(produto.preco);
    });
},
  • Our guy! thanks never thought it would be that simple. Thank you very much msm.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.