-1

I'm not so experienced in javascript, so I ask for a little help.

I have the following data array representation:

[name, obj1[name, type, obj2[name, type, obj3[name, type]]], obj4[name, type]]

Every object has properties as name and type.

The first name is the name of the main object. After that, if an object has another object inside, it opens new array for the properties of that object and potential other objects.

How can I iterate through this recursively and show this array in this way:

name(This can be left just as "name")
   name(of obj1)
   type(of obj1)
      name(of obj2)
      type(of obj2)
         name(of obj3)
         type(of obj3)
   name(of obj4)
   type(of obj4)

1 Answers1

1

I hope, the last example in this answer will help you to solve your problem. Looping through the tree with recursive function

var data = ['name1', 
  ['name2', 'type2', 
    ['name2.1', 'type2.1', 
      ['name2.1.1', 'type2.1.1']
    ]
  ], 
  ['name3', 'type3']
];

function eachRecursive(obj) {
  for (var k in obj) {
    if (typeof obj[k] == "object" && obj[k] !== null) {
      eachRecursive(obj[k]);
    }
    else {
      console.log(obj[k]); // here you will see in console all items from your array
      }
    }
}

eachRecursive(data);
Evgeniy
  • 19
  • 2
  • This should not be an answer but rather a comment. Give more context (an example) to beef this up or delete it. – Matt Oct 24 '18 at 16:24