我有一张地图daySubjects
和subject
数组我还有days
数组来存储' Sunday to Saturday
'
我必须使用这些变量
{
"daySubjects": {
"MONDAY": {
"subject": [
]
},
"TUESDAY": {
"subject": [
]
},
"WEDNESDAY": {
"subject": [
]
},
"THURSDAY": {
"subject": [
]
},
"FRIDAY": {
"subject": [
]
},
"SATURDAY": {
"subject": [
]
},
"SUNDAY": {
"subject": [
]
}
}
}
答案 0 :(得分:1)
好的,如果我正确理解了qustion,这里是简单的javascript代码示例:
var days = ["sun","mon","tue","wed","thu","fri","sat"];
var result = {
daySubjects : {}
};
days.forEach(
function(i){
result.daySubjects[i] = { subject:[] };
}
);
执行此行后,结果对象将包含:
{
"daySubjects": {
"sun": {
"subject": []
},
"mon": {
"subject": []
},
"tue": {
"subject": []
},
"wed": {
"subject": []
},
"thu": {
"subject": []
},
"fri": {
"subject": []
},
"sat": {
"subject": []
}
}
}
在javascript中,您必须注意定义您引用的对象。例如:
var test = {};
// fails because test.x is not defined
test.x[0] = 10;
//works cause you create array object before using it
test.x = [];
test.x[0] = 10;
更简单的是,您可以一次定义整个嵌套的JSON对象结构。