从列表中创建复杂数组

时间:2013-03-11 23:25:28

标签: javascript arrays multidimensional-array

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

[
    ["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”可能有所帮助,但我仍然希望它有一个heirarchy。

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

2 个答案:

答案 0 :(得分: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];

答案 1 :(得分:0)

使用来自@ 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,因为他发布了唯一的答案,我想给予一些赞助。