最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to declare nested objects in JavaScript? - Stack Overflow

programmeradmin6浏览0评论

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.

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.

Share Improve this question edited Jul 22, 2013 at 10:55 jeff asked Jul 22, 2013 at 0:17 jeffjeff 13.7k32 gold badges85 silver badges137 bronze badges 2
  • dictionaries.english_to_french = {english:"hello",french:"bonjour"} – elclanrs Commented Jul 22, 2013 at 0:19
  • The specification for an ObjectLiteral is a useful read. – RobG Commented Jul 22, 2013 at 3:12
Add a ment  | 

2 Answers 2

Reset to default 10

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

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.

发布评论

评论列表(0)

  1. 暂无评论