对一个对象数组的递归以创建自定义类对象

时间:2017-08-17 12:17:12

标签: javascript arrays recursion javascript-objects

我有一个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 个答案:

答案 0 :(得分: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())

答案 1 :(得分: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>