Access a property’s value through a String

Asked

Viewed 155 times

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 ispessoa.animais.gato, but I want the value to be accessed through a string. Something like: var gatoDoJoao = acessar(pessoa, "animais.gato");

3 answers

4

You can see that you understand that property names are just texts as keys to a array associative.

They are different properties at different levels, so one should access as different keys.

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

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

I put in the Github for future reference.

  • 1

    I know this method too, but I’m looking for a way to access the string in this "animals.gato" format, because this string comes from a text field. , as mentioned, a function that receives the object and the string. access(person, "animals.cat");

  • 1

    Then the question is another, you would have to analyze the string, separate it and use it the way I presented it. Your question does not clearly state that it needs to be so, it does not say what criteria, what to do when invalid text comes along, etc. So if the question is by this way it is unclear and is ample by asking for a complete solution. You could even ask a new more detailed question, but you would have to give all the necessary details and try to do it. Without criterion I would say that it is enough to make one split("."), but it’s a pretty naive way to solve this.

4


I finally managed to solve!

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

1

It has a slightly easier shape;

eval('pessoa.animais.gato');

The argument of the function Eval() is a string. If the string represents a expression, Eval() evaluates the expression. Whether the argument represents a or more Javascript statements, Eval() evaluates the statements. No call Eval() to evaluate an arithmetic expression; Javascript evaluates arithmetic expressions automatically.

MDN - EVAL

Browser other questions tagged

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