Recursive material name printing logic I have a function which goes through every name in an object. This object has an array parameter materials which holds other objects. Those objects have the same array parameter which hold more objects and so on.

My code lines 3-5 just repeat while adding .material and another variable. Also the code will only go into an object's name four layers down or else I have to keep repeating more code.

How can I cut down on this mess?

var itemList = function(x) {
    console.log(x.materials[0].name);
    for (var i = 1; i &lt; x.materials.length; i++) {
    console.log(x.materials[i].name);
       if (x.materials[i].build !== "BasicFactory" &amp;&amp; i !== 0) {
           for (var j = 1; j &lt; x.materials[i].materials.length; j++) {
               console.log(x.materials[i].materials[j].name);
               if (x.materials[i].materials[j].build !== "BasicFactory" &amp;&amp; j !== 0) {
                   for (var k = 1; k &lt; x.materials[i].materials[j].materials.length; k++) {
                   console.log(x.materials[i].materials[j].materials[k].name);
                   if (x.materials[i].materials[j].materials[k].build !== "BasicFactory" &amp;&amp; j !== 0) {
                       for (var l = 1; l &lt; x.materials[i].materials[j].materials[k].materials.length; l++) {
                       console.log(x.materials[i].materials[j].materials[k].materials[l].name);
                    }
                }
              }
            }
        }
    }
}
};
You could call itemList recursively for each object in x.materials:

var itemList = function(x) {
    for (var i = 0; i &lt; x.materials.length; i++) {
        console.log(x.materials[i].name);
        if (x.materials[i].build !== "BasicFactory" &amp;&amp; i !==0) {
            itemList(x.materials[i]);
        }
    }
};