2
\$\begingroup\$

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 < x.materials.length; i++) {
 console.log(x.materials[i].name);
 if (x.materials[i].build !== "BasicFactory" && i !== 0) {
 for (var j = 1; j < x.materials[i].materials.length; j++) {
 console.log(x.materials[i].materials[j].name);
 if (x.materials[i].materials[j].build !== "BasicFactory" && j !== 0) {
 for (var k = 1; k < 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" && j !== 0) {
 for (var l = 1; l < x.materials[i].materials[j].materials[k].materials.length; l++) {
 console.log(x.materials[i].materials[j].materials[k].materials[l].name);
 }
 }
 }
 }
 }
 }
}
};
Mathieu Guindon
75.5k18 gold badges194 silver badges467 bronze badges
asked Jan 17, 2015 at 11:41
\$\endgroup\$
0

1 Answer 1

4
\$\begingroup\$

You could call itemList recursively for each object in x.materials:

var itemList = function(x) {
 for (var i = 0; i < x.materials.length; i++) {
 console.log(x.materials[i].name);
 if (x.materials[i].build !== "BasicFactory" && i !==0) {
 itemList(x.materials[i]);
 }
 }
};
answered Jan 17, 2015 at 11:49
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.