创建一个从列表
问题描述:
复杂阵列如果我有类似这样的很多元素的数组:创建一个从列表
[
["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”可能会有所帮助,但我仍然喜欢它有一个层次。
我一直在抨击如何动态地将其转换为数组或对象结构。
答
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];
+0
请注意,我假设您问题中的最后一行数据是拼写错误,并且您在条目中始终有3个项目 – 2013-03-11 23:45:15
答
使用灵感来自@ 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,因为他发布了唯一的答案,我想提供一些功劳。
其他类别让我头疼。 – tymeJV 2013-03-11 23:37:50
听起来更像是你想让别人为你写代码而不是有特定的问题或问题。 您可以尝试创建对象的层次结构,创建对象,如:课程,课程类型,部门,主题和课程,然后将您的数组条目传递到基础对象上的addCourse函数,并解析它以决定是否将项目添加到现有对象如果部门,科目或课程不存在,则可以在层次结构中创建新的或创建新的部门。你仍然会得到你想要的树层次结构,但是你将能够将问题分解成更易于管理的块。 – 2013-03-11 23:44:50