gpt4 book ai didi

javascript - 是否可以定义一个包含对象的对象?

转载 作者:行者123 更新时间:2023-11-28 01:06:36 24 4
gpt4 key购买 nike

我有这个对象:

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"}
}

我意识到我可以像这样定义内部对象:

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

但是有没有一种方法可以定义可以具有任意数量的 IData 对象的整个对象?

最佳答案

如果 JSON 包含“stringId”(例如“1”、“2”)作为标识符,我们可以将该对象定义为字典(参见 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);
}

检查这个code here(点击运行,查看结果)

关于javascript - 是否可以定义一个包含对象的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25000239/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com