How do I access the value of this array in javascript?

Asked

Viewed 229 times

2

Good morning, I’m wanting to access the data of this array in javascript

[{"nome":"Teste","descricao":"Apenas um Teste","ativo":"1","id":6},[{"nome":"Categoria"}]]

and I’m not getting it, the way I’m using it is console.log(var[0].nome), on the console displays as Undefined

@Edit

my javascript code

function criaProduto(){
            prod = {
                nome: $('#nomeProduto').val() ,
                descricao: $('#descProduto').val(),
                codigo_barra: $('#codProduto').val(),
                ativo: 1,
                categoria_id: $('#categoriaProduto').val()
            };
            //console.log(prod);
            $.post("/api/produtos", prod, function(data){
                console.log(data)
                console.log(data[0]['nome'])
            });
        }

and php that makes the insertion of the data and the return

public function store(Request $request)
    {
        $prod = new Produto();
        $prod->nome = $request->input('nome');
        $prod->descricao = $request->input('descricao');
        $prod->codigo_barra = $request->input('codigo_barra');
        $prod->ativo = $request->input('ativo');
        $prod->categoria_id = $request->input('categoria_id');
        $prod->save();
        $cat_id = $request->input('categoria_id');
        $cat = Categoria::select('nome')->where('id', $cat_id)->get();
        $teste = array($prod, $cat);
        return json_encode($teste);
    }

Thank you in advance

  • Mark the correct answer when there is one, please

3 answers

3

You will access the same way in php:

var array = [{"nome":"Teste","descricao":"Apenas um Teste","ativo":"1","id":6},[{"nome":"Categoria"}]]

console.log(array[0]['nome'])

  • I updated my question, because I’m beginning to think I’m returning wrong... because it gave Undefined in this method that you passed

3


The problem is that you are not analyzing the JSON obtained from the server and so receive undefined when it does console.log(var[0].nome). Use the method JSON.parse() to parse a JSON string, constructing the value or a Javascript object described by the string.

const json = '[{"nome":"Teste","descricao":"Apenas um Teste","ativo":"1","id":6},[{"nome":"Categoria"}]]';

//Aqui faz a analise do JSON
const obj = JSON.parse(json);

//Descomente a próxima linha para "desfazer a análise do JSON" e obter o comportamento descrito na pergunta
//obj = json;

console.log(obj[0].nome);

console.log(obj[0].descricao);

console.log(obj[1][0].nome);

  • can access obj[0]. name but obj[1]. name as Undefined... sorry if it’s my stupid mistake, but by return it appears as if it’s an array inside the other, I’m a bit confused rs, I’ll try to copy the code and attaches in my question

  • @Faillen, Look at the syntax of your JSON for obj[1], the value is contained within another array you will have to access so obj[1][0]. name or adjust the formation of JSON in PHP

  • 1

    is managed here, with obj[1][0]. name, thank you, sorry for the beginner questions

0

if you are looking for json via ajax, try something like:

$.ajax({ type: "GET",   
     url: url,
     async: false,
     success : function(text)
     {
        response = text;
        if(jQuery.isEmptyObject(response)){
           alert('erro!');
        } else {
        console.log(response[0].nome)
     },
     error: function() { 
     } }).responseText;

Browser other questions tagged

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