2017-08-17 113 views
1

我有一個包含要傳遞給自定義類的參數的對象的javascript數組。通過對象數組進行遞歸以創建自定義類對象

var classObjectDetails = [{ 
     name: "objOne", 
     options: ["1","2"], 
     children: [{ 
     name: "childOne_objOne", 
     options: null 
     children: [{ 
      name: "childOne_childOne_objOne", 
      options: ["a", "b", "c", "d"], 
     }] 
     }, { 
     name: "childTwo_objOne", 
     options: null, 
     }] 
    }, { 
     name: "objTwo", 
     options: null, 
    }]; 

上面是包含詳細信息的示例對象。如果我有一類像下面,

class sampleClass { 
    constructor(objName, option) { 
     this.name = objName; 
     this.options = option; 
     this.children = []; 
     // Some other properties 
    } 
    // Some other functions 
} 

我想寫一個高效的遞歸函數裏面到底還給我sampleClass對象的數組。

objOne和objTwo是在陣列中的兩個對象,與具有objOne兩個孩子等作爲classObjectDetails

+2

你嘗試過這麼遠嗎? – marvel308

+1

嘗試,失敗,在此發佈。至少在調用自己的函數中做一個循環。 – user5014677

+1

您可以請發佈預期的輸出? –

回答

2

給出可以在原始數組使用從每個對象forEach()環路和使用數據來創建實例創建遞歸函數你的班級將擁有該班級的所有方法。

var data = [{"name":"objOne","options":["1","2"],"children":[{"name":"childOne_objOne","options":null,"children":[{"name":"childOne_childOne_objOne","options":["a","b","c","d"]}]},{"name":"childTwo_objOne","options":null}]},{"name":"objTwo","options":null}] 
 

 
class sampleClass { 
 
    constructor(objName, option) { 
 
    this.name = objName; 
 
    this.options = option; 
 
    this.children = []; 
 
    } 
 
    
 
    getName() { 
 
    return this.name; 
 
    } 
 
} 
 

 
function create(data) { 
 
    var result = []; 
 
    data.forEach(function(e) { 
 
    var o = new sampleClass; 
 
    o.name = e.name; 
 
    o.options = e.options 
 
    if (e.children) { 
 
     var children = create(e.children) 
 
     if (children.length) o.children = children; 
 
    } 
 
    result.push(o) 
 
    }) 
 
    return result; 
 
} 
 

 
var result = create(data); 
 
console.log(result) 
 
console.log(result[0].children[0].getName())

+0

謝謝,我解決孩子的問題。非常感謝你。 –

0
<script> 
var classObjectDetails = [ 
    { 
     name: "objOne", 
     options: ["1","2"], 
     children: [ 
     { 
     name: "childOne_objOne", 
     options: null, 
     children: [ 
      { 
       name: "childOne_childOne_objOne", 
       options: ["a", "b", "c", "d"], 
      } 
     ] 
     }, 
     { 
     name: "childTwo_objOne", 
     options: null, 
     } 
     ] 
    }, 

    { 
     name: "objTwo", 
     options: null, 
    }]; 

function parseJSONTosampleClass(classObjectDetail){ 
    var sampleClasList = []; 
    for (var key in classObjectDetail) { 
     var child = classObjectDetail[key]; 
     var obj = new sampleClass(); 
     sampleClasList.push(obj); 
     obj.name = child["name"]; 
     obj.options = child["options"]; 
     obj.children = parseJSONTosampleClass(child["children"]); 
    } 

    return sampleClasList; 
} 
class sampleClass { 
constructor(objName, option) { 
     this.name = objName; 
     this.options = option; 
     this.children = []; 
    } 
} 

parseJSONTosampleClass(classObjectDetails); 

</script>