0

I am doing a little multi language change, here is the code jsfiddle
html and jQuery:

var dict = {
 fr: {
   'hello' : 'Bonjour',
        'bye' : 'Au revoir'
  },
  en: {
   'hello' : 'Hello',
        'bye' : 'Bye'
  }
};

function text (lang){
 $('h1').html(dict.lang.hello);
        $('p').html(dict.lang.bye);
};

$('a').click(function (){
 var selected = $(this).attr('title');
        text(selected);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#/" title="fr">fr</a>
<a href="#/" title="en">en</a>
<h1>Bonjour</h1>
<p>Au revoir</p>

What I want is: click the "en" or "fr" to change text from the "dict" object, I stored the "title" of the <a> tag, but when I put it to the function "text" as parameter, the console shows "TypeError: dict.lang is undefined", I understand that the var selected is a string, it can't not replace the "fr" and "en" in the object.
So here is the question:
how to convert a string to object's property which it's an object too?

Jiang Lan
  • 171
  • 1
  • 12

2 Answers2

2

Use it as dict[lang].hello and dict[lang].bye

var dict = {
 fr: {
   'hello' : 'Bonjour',
        'bye' : 'Au revoir'
  },
  en: {
   'hello' : 'Hello',
        'bye' : 'Bye'
  }
};

function text (lang){
 $('h1').html(dict[lang].hello);
        $('p').html(dict[lang].bye);
};

$('a').click(function (){
 var selected = $(this).attr('title');
        text(selected);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#/" title="fr">fr</a>
<a href="#/" title="en">en</a>
<h1>Bonjour</h1>
<p>Au revoir</p>
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
1

Since, there are not lang props on your dict variabel. so you need to remove it.

Refers from here, you can accessing props of object as associative array. as example: array["name"]["nameagain"].id;

so for your case, you can call it using: dict[lang] to get the object, or dict[lang].bye as particular data.

See my snippet below:

var dict = {
 fr: {
   'hello' : 'Bonjour',
        'bye' : 'Au revoir'
  },
  en: {
   'hello' : 'Hello',
        'bye' : 'Bye'
  }
};

function text (lang){
 $('h1').html(dict[lang].hello);
        $('p').html(dict[lang].bye);
};

$('a').click(function (){
 var selected = $(this).attr('title');
        text(selected);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#/" title="fr">fr</a>
<a href="#/" title="en">en</a>
<h1>Bonjour</h1>
<p>Au revoir</p>
Fadhly Permata
  • 1,686
  • 13
  • 26