how to access a value of a specific property of an object in js

1

I have a multidimensional object in javascript that I want to access and get a value of a specific property but when trying to get the value it gives me an error "Can not read property 0 of undefined", what is the error.

        var objeto2 = {
            nameKey: [{ nombre: "csrf_name", valor: "csrf5b91a8e01e786" }],
            valueKey: 
                [{
                    nombre: "csrf_value",
                    valor: "e70a02a75a53e5934af65685897e0d71"
                }]

        };

        var v1 = objeto2.namekey[0].valor;
        var v2 = objeto2.valueKey[0].valor;
    
asked by jose miguel jara 07.09.2018 в 00:50
source

2 answers

4

Javascript is case sensitive. So it is a different variable with lower case or upper case:

var objeto2 = {
            nameKey: [{ nombre: "csrf_name", valor: "csrf5b91a8e01e786" }],
            valueKey: 
                [{
                    nombre: "csrf_value",
                    valor: "e70a02a75a53e5934af65685897e0d71"
                }]

        };

        var v1 = objeto2.nameKey[0].valor;
        var v2 = objeto2.valueKey[0].valor;
        console.log(v1);
        console.log(v2);
    
answered by 07.09.2018 / 00:52
source
0

I just want to add that you can also access the properties of an object using [<string>] , it is useful when the property is in a variable, for example when it is dynamic or if we are in for in for example.

Anyway, whenever possible, it is better to access using the dot notation, as the answer of alanfcm says, because just by seeing it we already realize the structure of the object:

var objeto2 = {
            nameKey: [{ nombre: "csrf_name", valor: "csrf5b91a8e01e786" }],
            valueKey: 
                [{
                    nombre: "csrf_value",
                    valor: "e70a02a75a53e5934af65685897e0d71"
                }]

        };
                
        let clave1 = "nameKey";
        let clave3 = "valor"

        //alternativa a la notación de punto
        console.log(objeto2[clave1][0][clave3]);
        console.log(objeto2["valueKey"][0]["valor"]);
     
        
        
    
answered by 07.09.2018 в 01:15