Skip to content Skip to sidebar Skip to footer

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'

Solution 1:

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);

Solution 2:

In order to nest two or more objects, the objects need to have an attribute assigned to them. For example,

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

"hello" at the beginning of the object would be the attribute. Then the object is its value. So that way you can access the object by accessing its attribute. Just putting an object in an object does not work. That's why you're getting your error.

Post a Comment for "How To Declare Nested Objects In Javascript?"