Is it possible to define an object containing objects?

后端 未结 2 1177
囚心锁ツ
囚心锁ツ 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);

    0 讨论(0)
  • 2021-01-23 14:56

    In case, that the JSON contains "stringId" (e.g. "1", "2") as an identificator, we can define that object as a dictionary (see it here):

    interface IData 
    {
        topicId: number;
        subTopicId: number;
        topicName: string;
        subTopicName; string;
    }
    // IDictionary with a key of type string
    //              and a value of type IData
    interface IDataSet
    {
        [key: string] : IData;
    } 
    
    var source = 
    '{  "1":{"topicId":1, "subTopicId":1, "topicName":"x","subTopicName":"x"},'+
    '   "2":{"topicId":1, "subTopicId":2, "topicName":"x","subTopicName":"x"},'+
    '  "62":{"topicId":10,"subTopicId":62,"topicName":"x","subTopicName":"x"}'+
    '}';
    
    var a = <IDataSet>JSON.parse(source);
    
    for(var key in a)
    {
        var elm = document.createElement('div');
        elm.innerText = "key: " + key + ", topicId: " + a[key].topicId  
        document.body.appendChild(elm);
    }
    

    Check this code here (click run, to see the results)

    0 讨论(0)
提交回复
热议问题