-2

I have been working with an application that i have to use JQuery. And i have an issue my functions related to sons and grandsons in my below mentioned code:

If i type into my browser http://localhost:8080/fathers

Edited

I get :

[{"id":1,"fname":"fname","lname":"lname","sons":[{"id":1,"fname":"fname","lname":"lname","grandsons":[{"id":1,"fname":"fname","lname":"lname"}]}]}]

With my current $.getJSON i get the following output:

for sons:[objtct Object] for grandsons: undefined

Cœur
  • 37,241
  • 25
  • 195
  • 267
propro
  • 17
  • 4
  • So the first problem is that your quoted JSON is invalid. It's missing a `}]` at the end. Separately, `for-in` is not for looping through arrays; see [this question's answers](https://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript) for how to loop through arrays. Also note that your quoted structure, with `}]` at the end, is a *nested* structure, not just a flat array; your code does nothing to handle that. – T.J. Crowder Aug 11 '17 at 10:33
  • because `data[i].sons` is an array of object(s), and `data[i].grandsons` doesn't exist according to the JSOn you've shown, it is a property of `data[i].sons` – Jaromanda X Aug 11 '17 at 10:33
  • Given your Java classes, `sons` will be an array, hence the `object` output, and there is no `grandsons` property, hence undefined. `grandsons` is a property of the `son` class. – Rory McCrossan Aug 11 '17 at 10:33
  • @propro you have to know that every time `$('#tag')` is executed, it computes stuff, searches the element in the DOM and creates a jQuery object. This is heavy. Instead of writing `$('#tag') $('#tag') $('#tag') $('#tag')`, cache it by storing it in a variable : `var $tag = $('#tag')`, then reuse it. `$tag.append(...)`. You can also chain commands : `$tag.append(...).append(...).append(...).append(...)`. Massive code improvement. – Jeremy Thille Aug 11 '17 at 10:48
  • Also, why don't you use jQuery everywhere? Like, instead of `document.getElementById("fname").value`, why don't you just use `$("#fname").val()` ? – Jeremy Thille Aug 11 '17 at 10:55

1 Answers1

0

data[i].sons is an array, when you put an array directly inside html it outputs [objtct Object]

for(var i in data){
  var sons = data[i].sons;
  for(var j in sons){ 
    var son = sons[j];
    var grandsons = son.grandsons;
    for(var k in grandsons){
      var grandson = grandsons[k];
    }
  }
}

In your case try:

$('#tag').append("<p>sons: " + data[i].sons.map(son => son.fname + ' ' + son.lname).join(', ') + "</p>")

and

var grandsons = data[i].sons.map(son => son.grandsons.map(grandson=>grandson.fname + ' ' + grandson.lname))
$('#tag').append("<p>grandsons: " + [].concat.apply([], grandsons).join(', ') + "</p>")
Ben Tahar
  • 69
  • 4
  • I think you need to create form and serialize it, you can find easy tutorials for that. What you shouldn't do is get the value the way you're doing right now. – Ben Tahar Aug 11 '17 at 15:30