2017-08-17 65 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>