Amit Kumar Amit Kumar - 1 year ago 49
Javascript Question

Recursion over an array of object to create custom class object

I have an javascript array of object containing some parameters to be passed to custom class.

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,
}];


Above is sample object containing details. If i have a class like below,

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


I want to write an efficient recursive function which in the end return me the array of sampleClass object.

objOne and objTwo being two object in array, with objOne having two children and so on as given in the
classObjectDetails

Answer Source

You can create recursive function using forEach() loop and use data from each object in original array to create instance of your class that will have all methods of that class.

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())

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download