Search code examples
javascripthierarchy

Access child Object in js


function Luminary(radius, orbitRadius, speed, children) {
    this.radius = radius;
    this.orbitRadius = orbitRadius;
    this.speed = speed;
    this.children = children;
}

function initSolarSystem() {
    var moon = new Luminary(0.02, 0.2, 0.0015, []);
    var earth = new Luminary(0.1, 0.7, 0.001, [moon]);
    var sun = new Luminary(0.3, 0.0, 0.0, [earth]);
    return sun;
}

var solarSystem = initSolarSystem();
  1. I have the code above in JS. How can I access for example the radius of earth using the solarSystem object? The following returns Undefined alert(solarSystem.children.radius);

  2. How should I call children in a recursive function as follows:

    function draw(obj) {
        // draw Current Object 
        if (obj.children != undefined) {
          draw(obj.children);
        }
    }
    
    draw(solarSystem);
    

Can Someone please help me?


Solution

  • I have the code above in JS. How can I access for example the radius of earth using the solarSystem object? The following returns Undefined alert(solarSystem.children.radius);

    solarSystem.children is an array, so use solarSystem.children[0].radius

    How should I call children in a recursive function as follows.

    function draw(obj) 
    {
      // draw Current Object
    
      if (obj.children != undefined) 
      {
        obj.children.forEach( s => draw(s) ); //invoke draw in a loop
        //draw(obj.children[0]); //use 
      }
    }
    
    draw(solarSystem);