Access value of a property using a String

3

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");

    
asked by anonymous 28.11.2016 / 02:16

3 answers

4

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);
    
28.11.2016 / 03:09
4

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"]);
    
28.11.2016 / 02:24
1

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

    
29.11.2016 / 11:58