Redmond Seyer
Redmond Seyer

Reputation: 55

Parse JSON using recursive and for loop

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

Item 01
 SubItem 01
  InnerSubItem 01

Item 02
 SubItem 01
  InnerSubItem 01

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

$.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)
    }
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 0

Views: 78

Answers (1)

H77
H77

Reputation: 5967

Your code breaks when the object doesn't have a layers property. You should check for its existence before checking for length.

e.g.

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

Fixed code:

$.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);
    }
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

On a side note, you don't seem to be using the reversed array and are unnecessarily passing data each time you call repeat. You could probably write something like this instead (reverse the array if you need to):

$.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]);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

Related Questions