0

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>

1
  • JSON is like of native in javascript. u can simply use JSON.parse(data) to parse json data to js object. Commented Dec 18, 2017 at 8:13

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.