0

如果我有一个包含许多类似于此的项目的数组:

[
    ["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"]
]

结构本质上是“部门->主题->课程”。

我想动态创建一个类似于以下(或任何最有意义的)的数组(或对象)......

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

“其他”部门不一定遵循“主题->课程”,而是可以有“主题->主题->课程”和“主题->课程”。也许添加一个 type="course" 和 type="subject" 可能会有所帮助,但我仍然希望它有一个层次结构。

我一直在思考如何将其动态转换为数组或对象结构。

4

2 回答 2

1
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-11T23:41:56.130 回答
0

使用来自@ben336、@user1787152 以及DevShed 论坛主题的灵感,我想出了以下代码:

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,因为他发布了唯一的答案,我想给予一些信任。

于 2013-03-13T18:50:45.557 回答