How to declare nested objects in JavaScript?

I am trying to create an object containing 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 specify what I want to do. Edited code above.

+4
source share
2 answers

You are trying to pass your object to a property, and this property will be the only object:

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

You do not need extra { } . You can immediately declare everything:

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

I would suggest that the best format for your dictionaries might be:

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

This way you can directly search for words without searching. Then you can create a reverse dictionary:

 dictionaries.french_to_english = function(dict) { var rv = {}; for (var eword in dict) rv[dict[eword]] = eword; return rv; }(dictionaries.english_to_french); 
+5
source

To nest two or more objects, the objects must have an attribute assigned to them. For instance,

 { "hello":{ "english":"hello", "french":"bonjour", "portuguese":"ola" }, "good day":{...}, "how are you":{...} } 

β€œhello” at the beginning of the object will be an attribute. Then the object is its value. Thus, you can access the object by accessing its attribute. Just placing the object in the object does not work. That is why you get your mistake.

0
source

Source: https://habr.com/ru/post/1492620/


All Articles