1
var example= {
        'fr' : {
            name: "France",
            country: "europe",
        },
        'es' : {
            name: "Espana",
            pre: "europe",
        },
    };

I would like to find an array name using a variable. Here there is an example that doesn't work:

var select = 'country';
console.log(example['fr'].select);

I would like that this piece of code return "europe", but it doesn't. How could I do in a simple way?

user1392191
  • 117
  • 1
  • 8

3 Answers3

6

Do it like this:

var select = 'country';
console.log(example['fr'][select]);
yakxxx
  • 2,841
  • 2
  • 21
  • 22
4
console.log(example['fr'][select]);

maybe?

Michael Krelin - hacker
  • 138,757
  • 24
  • 193
  • 173
1

The problem with your code is that you are using wrong syntax. You have a two-dimensional array, i.e. array nested in another array. So, the expression example['fr'] returns you an array with two members:

{
   name: "France",
   country: "europe",
}

and you have to get the value bound to country key from it like this:

ar2 = example['fr'];
console.log(ar[select]);

or to make it more concise:

console.log(example['fr'][select]);

directly referring to the element of the innermost array without using a temporary variable.

akhilless
  • 3,169
  • 19
  • 24