Access attribute of a JS object using the key of another attribute

Asked

Viewed 1,899 times

0

I’m trying to get the value inside a given object using the key of another object: Ex:

I have the objects:

var obj1 = { id:'gh73f'}

var obj2 = {
    gh73f : 123,
    h39sg : 764,
    c9wer : 921
}

I tried to:

var valor = obj2[obj1.id];

and

var valor = obj2[obj1[id]];

In none of the cases can I get the key value gh73f of obj2.

  • 4

    In firefox, the first way var valor = obj2[obj1.id] worked normally... For the second way to work, it should be var valor = obj2[obj1['id']].

  • 1

    The first form should work on any and all Javascript interpreters. You didn’t get it with any specific browser, or some engine like Node.js?

  • 2

    The first try really should work

1 answer

2

Do the following use the eval, mount the string and after the eval for it to execute as code:

var valor = eval("obj2."+obj1.id);
  • 2

    That’s a cannon shot to kill a fly.

  • @Renan yes, but do you have any better solution? if you have please share with us.

  • View comments on the question.

  • 3

    @Renan but at least the fly dies is better than the fly having many puppies like in the movie Godzilla that the giant cockroaches had many children but Godzilla ended up with all and Godzilla would be the eval and the problem would be the giant cockroach, intende?

  • Why am I negative? Tell me what’s wrong with my answer?

Browser other questions tagged

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