Access value of a property using a String

Posted on

Question :

Suppose I have the following object:

var pessoa = {
    nome: "João",
    animais: {
        cachorro: "Rex",
        gato: "Pipoca",
    }
}

I need a function to do something like this:

var gatoDoJoao = pessoa["animais.gato"];

I know that in this example the correct is pessoa.animais.gato , but I want the value to be accessed through a string.
Something like: var gatoDoJoao = acessar(pessoa, "animais.gato");

    

Answer :

I finally got it resolved!

var obj = {
    nome: "João",
    animais: {
        gato: "Foo",
        cachorro: "Bar"
    }
};

function acessar(obj, prop){
    var tmp = obj;
    var campos = prop.split(".");

    for(var i in campos){
        if(tmp.hasOwnProperty(campos[i])){
            tmp = tmp[campos[i]];
        }else{
            return false;
        }
    }

    return tmp;
}

var nomeDoGato = acessar(obj, "animais.gato");
console.log(nomeDoGato);

    

You see that property names are just texts as keys of an associative array .

They are different properties at different levels, so they should be accessed as different keys.

var pessoa = {
    nome: "João",
    animais: {
        cachorro: "Rex",
        gato: "Pipoca",
    }
}

console.log(pessoa["animais"]["gato"]);

    

It has a slightly easier way;

eval('pessoa.animais.gato');

  

The argument to the eval () function is a string. If the string represents a
  expression, eval () evaluates the expression. If the argument represents one or
  more JavaScript declarations, eval () evaluates the declarations. Not
  call eval () to evaluate an arithmetic expression; JavaScript
  evaluates arithmetic expressions automatically.

MDN-EVAL

    

Leave a Reply

Your email address will not be published. Required fields are marked *