0

I am trying to get access to a object over a variable. I´ve a object saved in lang that looks like that:

{TeamspeakControl: "Teamspeak Control"}

Now I want to get the string out over a variable like:

console.log(lang["TeamspeakControl"]);

If I run this now I get the error in the console:

Uncaught TypeError: Cannot read property 'TeamspeakControl' of undefined

Has someone a idea?

var lang = {TeamspeakControl: "Teamspeak Control"};
$('lang').each(function() {
  console.log(lang[$(this).attr('label')]);
  $(this).html(lang[$(this).attr('label')]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://rawgit.com/utatti/perfect-scrollbar/master/css/perfect-scrollbar.css" rel="stylesheet"/>
<script src="https://rawgit.com/utatti/perfect-scrollbar/master/dist/perfect-scrollbar.js"></script>
<lang label="TeamspeakControl"></lang>

There it works. Looks like my get is async and is to slow. This is how my lang object will be filled.

    var lang = Object();
    $.get('lang', function(data) {
        lang = data;
    });
Liam
  • 27,717
  • 28
  • 128
  • 190
Lukas Gund
  • 639
  • 1
  • 9
  • 27

2 Answers2

0

Looks like it works, if I make it asynchronous like this:

    $.get('lang', function(data) {
        var lang = data;
        $('lang').each(function() {
            $(this).html(lang[$(this).attr('label')]);
        });
    });

But is that a good solution?

George
  • 6,630
  • 2
  • 29
  • 36
Lukas Gund
  • 639
  • 1
  • 9
  • 27
-1

Strange... It works for me:

var lang = {TeamspeakControl: "Teamspeak Control"};
console.log(lang["TeamspeakControl"]);

In general, you're doing right, you only have to pay attention that you assign object to variable in same scope where you run console.log.

In your case you can console.log only inside callback even it's slow:

var lang = Object();
$.get('lang', function(data) {
    lang = data;
    console.log(lang);
});
cn007b
  • 16,596
  • 7
  • 59
  • 74