0

Say I have a json object that looks like

"bounds":{
    "coordinatetop":{
       "x":143,
       "y":544
    },
    "coordinatebottom":{
       "x":140,
       "y":510
    }
}

I am trying to parse the JSON currently with this code, where data is the json data and target is just an tag id.

$.each(data, function(index, value) {
    if (typeof(value) == 'object') {
      processBounds(value, target);
    } else {
      console.log(value);
    }
});

When I loop through this, the function call takes the values coordinatetop and target, followed by the value of x and y which are 143 and 544. However, this function does not loop far enough to get the values of coordinatebottom.

What are other ways of implementation to make that possible? Thanks

Simon2233
  • 113
  • 1
  • 9
  • Question unclear. When I try to reproduce your issue it logs the entire object (https://jsfiddle.net/5hy9zbmu/). Which means ive made assumptions about your code which is wrong. This is why we ask for a [mcve] – Jamiec Jul 20 '17 at 15:07
  • That's not [JSON](http://json.org). _"JSON is a textual, language-indepedent data-exchange format, much like XML, CSV or YAML."_ -> [What is the difference between JSON and Object Literal Notation?](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation) – Andreas Jul 20 '17 at 15:10
  • @Andreas sigh. Yes we know. People use the term interchangably and ive experienced confusion exactly zero times as to what they mean – Jamiec Jul 20 '17 at 15:10
  • A new example I wrote to explain recursion: The Tic tac box problem. Boxes inside boxes. http://output.jsbin.com/lemusan/8/ – Emmanuel Delay Jul 20 '17 at 15:48

1 Answers1

0

In fact you aren't calling the function recursively, you are just binding a callback function that calls processBounds() function.

You need to declare the processBounds function separately then bind it in the .each callback:

var processBounds = function(index, value) {
  if (typeof(value) == 'object') {
    processBounds(value, target);
  } else {
    console.log(value);
  }
}

$.each(data, processBounds);

Edit:

$.each(data.bounds, processBounds);
cнŝdk
  • 31,391
  • 7
  • 56
  • 78
  • sorry, I forgot to state that the $.each is located inside a processBounds(data, target) function – Simon2233 Jul 20 '17 at 15:13
  • @Simon2233 So in that case you need to call it with `data.bounds`. – cнŝdk Jul 20 '17 at 15:15
  • yes I have done that. I have no trouble printing the contents of coordinatetop but im unable to access contents of coordinatebottom i assume because of the recursive function call stopping the loop – Simon2233 Jul 20 '17 at 15:20