Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare nested objects in JavaScript?

I'm trying to create an object that contains an object, so think of it as a dictionary:

var dictionaries = {};
dictionaries.english_to_french =
{
 {english:"hello",french:"bonjour"},
 {english:"i want",french:"je veux"},
 {english:"bla",french:"le bla"}
};

but it gives the error Uncaught SyntaxError: Unexpected token { what am I doing wrong?

Thanks !

Edit

I'm sorry that I did not clarify what I want to do. Edited the code above.

like image 840
jeff Avatar asked Jul 22 '13 00:07

jeff


1 Answers

You're trying to give your object a property, and that property will be a single object:

dictionaries.english_to_french =
  {english:"hello",french:"bonjour"}
;

You don't need the extra { }. You could declare the whole thing at once:

var dictionaries = {
  english_to_french: {
    english: "hello", french: "bonjour"
  }
};

I would suggest that a better format for your dictionaries might be:

var dictionaries = {
  english_to_french: {
    "hello": "bonjour",
    "chicken": "poulet", // ? something like that
    "Englishman": "rosbif"
  }
};

That way you can look up words directly without having to search. You could then create the reverse dictionary from that:

dictionaries.french_to_english = function(dict) {
  var rv = {};
  for (var eword in dict)
    rv[dict[eword]] = eword;
  return rv;
}(dictionaries.english_to_french);
like image 128
Pointy Avatar answered Sep 25 '22 08:09

Pointy