0

I'm trying to build a tree using JSON for which i'm trying to just print in browser console.

var json = [{
  name: "1",
  id: 1,
  child: [{
    name: "11",
    id: 11,
    child: [{
      name: "111",
      id: 111
    }, {
      name: "112",
      id: 112
    }]
  }, {
    name: "12",
    id: 12
  }]
}];

function ya(obj) {
  console.log(obj.name);
  if (obj.child) {
    console.log("length=" + obj.child.length);
    for (i = 0; i < obj.child.length; i++) {
      ya(obj.child[i]);
    }
  }
}
ya(JSON.parse(JSON.stringify(json))[0]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Here I would like to print

1
11
111
112
12

in console. But it only prints

1
11
111
112

I want to do this recursively. How can I achieve this?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555

1 Answers1

0

You need to declare i with var:

for (var i = 0; i < obj.child.length; i++)

See Difference between variable declaration syntaxes in Javascript (including global variables)? for more details.

Community
  • 1
  • 1
sp00m
  • 47,968
  • 31
  • 142
  • 252