Вопрос

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?

Это было полезно?

Решение

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)

Другие советы

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

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top