Is it possible to define an object containing objects?

后端 未结 2 1178
囚心锁ツ
囚心锁ツ 2021-01-23 14:34

I have this object:

var a = {
 \"1\":{\"topicId\":1,
      \"subTopicId\":1,
      \"topicName\":\"x\",
      \"subTopicName\":\"x\"},
 \"2\":{\"topicId\":1,
            


        
2条回答
  •  孤独总比滥情好
    2021-01-23 14:49

    Whoops, overlooked the typescript label.. see alternate answer for way to do it by parsing JSON (which could have been output by server, reading from config file, etc.). Here is how to do it in pure javascript:

    Use an array property inside your object.

    Then set each array element to an instance of the IData object.

    var a = { Topics: [] }; // define container with empty Topics array
    
    // add some topics
    a.Topics[1] = { topicId: 1, subTopicId: 1, topicName: "x", subTopicName: "x" };
    a.Topics[2] = { topicId: 1, subTopicId: 2, topicName: "x", subTopicName: "x" };
    a.Topics[62] = { topicId: 10, subTopicId: 62, topicName: "x", subTopicName: "x" };
    

    Then access the objects like this:

    alert(a.Topics[1].topicName + " - " + a.Topics[1].subTopicName);

提交回复
热议问题