如果我有一个数组,其中有很多类似下面这样的项:
[
["Core", "Mathematics", "Mathematics 20-4"],
["Core", "Mathematics", "Mathematics 30-1"],
["Other", "Fine Arts", "Art", "some art course"],
["Other", "Fine Arts", "Music", "some music course"],
["Other", "Forensics", "some forensics course"],
["French Immersion", "Core", "Mathématiques", "Mathématiques 30-1"]
]其中结构本质上是“系-> Subject -> Course”。
我想动态创建一个类似下面(或最有意义的)的数组(或对象)……
{
subjects: [
{
title: "Mathematics", courses: [ "Mathematics 20-4", "Mathematics 30-1" ]
},
{
title: "Mathématiques", lang: "fr", courses: [ "Mathématiques 30-1" ]
}
],
other: {
subjects: [
{
title: "Forensics", courses: [ "some forensics course" ]
},
{
title: "Fine Arts", subjects: [
{
title: "Art", courses: [ "some art course" ]
},
{
title: "Music", courses: [ "some music course" ]
}
]
}
]
}
}“其他”部门不一定遵循"Subject -> Course“,而是可以有"Subject -> Subject -> Course”和"Subject -> Course“。也许添加type="course“和type="subject”可能会有所帮助,但我仍然希望它具有继承性。
我一直在苦苦思索如何将其动态转换为数组或对象结构。
发布于 2013-03-12 07:41:56
var courses = {};
for(var i =0; i<arr.length; i++){
var department = arr[i][0];
var subject = arr[i][1];
var course = arr[i][2];
courses[department]= courses[department] || {};
courses[department][subject] = courses[department][subject] || [];
courses[department][subject].push(course);
},它将在表单中生成一个对象
courses = {
core:{
mathematics:["math1","math2"],
english: ["english1,"english2"]
}
Other:{
"Fine Arts":[...],
"Forensics":[...]
}
}我想这就是你想要的。
然后,如果您想要一个特定主题的课程数组,则可以使用
var courselist = courses[<department>][<subject];发布于 2013-03-14 02:50:46
根据@ben336、@user1787152和DevShed forum thread的启发,我想出了以下代码:
var Department,
departments = [];
Department = function(title) {
this.title = title;
this.subjects = [];
};
function parseTitles( titles )
{
var i, department, departmentTitle,
hasDepartment = false;
departmentTitle = titles.shift();
for (i=0; i<departments.length; i++) {
if (departments[i].title === departmentTitle) {
hasDepartment = true;
break;
}
}
if (!hasDepartment) {
department = new Department(departmentTitle);
departments.push(department);
}
departments[i].subjects = titles;
}主题被用作导航的一种形式,课程通过JSON查询。我将主题保存为一个数组,当单击主题数组中的最后一个子对象时,它将查询JSON以获取该主题的课程。
我会看看我是否可以给@ben336信任,因为他发布了唯一的答案,我想给一些信任。
https://stackoverflow.com/questions/15350553
复制相似问题