user3568783
user3568783

Reputation:

Is it possible to define an object containing objects?

I have this object:

var a = {
 "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"}
}

I realize I can define the inside objects like this:

interface IData {
    topicId: number;
    subTopicId: number;
    topicName: string;
    subTopicName; string;
}

But is there a way that I can define the whole objects which can have any number of IData objects?

Upvotes: 1

Views: 4476

Answers (2)

nothingisnecessary
nothingisnecessary

Reputation: 6233

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

Upvotes: 0

Radim Köhler
Radim Köhler

Reputation: 123891

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)

Upvotes: 2

Related Questions