我有一个 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
您可以使用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())
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句