2013-03-11 249 views
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」可能會有所幫助,但我仍然喜歡它有一個層次。

我一直在抨擊如何動態地將其轉換爲數組或對象結構。

+0

其他類別讓我頭疼。 – tymeJV 2013-03-11 23:37:50

+0

聽起來更像是你想讓別人爲你寫代碼而不是有特定的問題或問題。 您可以嘗試創建對象的層次結構,創建對象,如:課程,課程類型,部門,主題和課程,然後將您的數組條目傳遞到基礎對象上的addCourse函數,並解析它以決定是否將項目添加到現有對象如果部門,科目或課程不存在,則可以在層次結構中創建新的或創建新的部門。你仍然會得到你想要的樹層次結構,但是你將能夠將問題分解成更易於管理的塊。 – 2013-03-11 23:44:50

回答

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]; 
+0

請注意,我假設您問題中的最後一行數據是拼寫錯誤,並且您在條目中始終有3個項目 – 2013-03-11 23:45:15

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,因爲他發佈了唯一的答案,我想提供一些功勞。