Parse JSON using recursive and for loop

时间:2017-12-18 08:08:19

标签: javascript json

I have a JSON to parse. I'm trying to use recursive method here.The current JSON has a structure similar to the bottom one

plumbing

Using the function I created, I'm able to parse only the first set (Contents under Item 01). The code doesn't comes back to the loop when is condition is false

Code used

Item 01
 SubItem 01
  InnerSubItem 01

Item 02
 SubItem 01
  InnerSubItem 01
$.getJSON('https://api.myjson.com/bins/6atbz', function(data) {
  repeat(data, data.layers);
})

function repeat(data, x) {
  var layer = data.layers.reverse()
  for (i = 0; i < x.length; i++) {
    name = x[i].name
    console.log(name)
    if (x[i].layers.length > 0) {
      repeat(data, x[i].layers)
    }
  }
}

1 个答案:

答案 0 :(得分:1)

当对象没有layers属性时,代码会中断。在检查length之前,您应该检查它的存在。

e.g。

if (x[i].layers && x[i].layers.length > 0)

固定代码:

&#13;
&#13;
$.getJSON('https://api.myjson.com/bins/6atbz', function(data) {
  repeat(data, data.layers);
})

function repeat(data, x) {
  var layer = data.layers.reverse();
  for (var i = 0; i < x.length; i++) {
    name = x[i].name;
    console.log(name);
    if (x[i].layers && x[i].layers.length > 0) {
      repeat(data, x[i].layers);
    }
  }
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

另一方面,您似乎没有使用反向数组,每次拨打data时都会不必要地传递repeat。您可能会写这样的东西(如果需要,可以反转数组):

&#13;
&#13;
$.getJSON('https://api.myjson.com/bins/6atbz', function(data) {
  repeat(data);
})

function repeat(data) {
  if (!data || !data.layers)
    return;

  var x = data.layers;
  for (var i = 0; i < x.length; i++) {
    name = x[i].name;
    console.log(name);
    repeat(x[i]);
  }
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;