0

I have a HTML table, I want to fill it up with a JSON Object. Printing the object works, but I can't get the arrays seperately. When I try to get the value of one 'ingredient' it keeps saying undefined. What's wrong in my code?

JQ:

function loadIngredients() {
    $.get("js/test.json", (data) => {
        console.log(data);
        $.each(data, function (index) {
            console.log(this.ingredient);
        });
    });
}

JSON:

{
"data":[
    {"ingredient":"Banaan", "hoeveelheid":"50", "energie":"89", "vet":"0,9", "verzagigd vet":"0,3", "eiwit":"1,2", "koolhydraten":"20,4", "vezels":"1,9", "zout":"0,0"}, 
    {"ingredient":"Appel", "hoeveelheid":"80", "energie":"77", "vet":"0,6", "verzagigd vet":"0,1", "eiwit":"1,1", "koolhydraten":"15,6", "vezels":"2,5", "zout":"0,1"}, 
    {"ingredient":"Brood", "hoeveelheid":"120", "energie":"320", "vet":"1,1", "verzagigd vet":"0,4", "eiwit":"7,4", "koolhydraten":"30,6", "vezels":"4,8", "zout":"0,8"}
]
}
2
  • I think this is what you are looking for: </br> <a href="stackoverflow.com/questions/1078118/…> Commented Jun 6, 2017 at 15:00
  • @sagarman you should really make sure that link works Commented Jun 6, 2017 at 15:08

1 Answer 1

1

The "data" in your $.each loop is not is the variable that contains the {}. Try use data.data

 $.each(data.data, function(index) {
   console.log(this.ingredient);
 });

var data = {
  "data": [{
      "ingredient": "Banaan",
      "hoeveelheid": "50",
      "energie": "89",
      "vet": "0,9",
      "verzagigd vet": "0,3",
      "eiwit": "1,2",
      "koolhydraten": "20,4",
      "vezels": "1,9",
      "zout": "0,0"
    },
    {
      "ingredient": "Appel",
      "hoeveelheid": "80",
      "energie": "77",
      "vet": "0,6",
      "verzagigd vet": "0,1",
      "eiwit": "1,1",
      "koolhydraten": "15,6",
      "vezels": "2,5",
      "zout": "0,1"
    },
    {
      "ingredient": "Brood",
      "hoeveelheid": "120",
      "energie": "320",
      "vet": "1,1",
      "verzagigd vet": "0,4",
      "eiwit": "7,4",
      "koolhydraten": "30,6",
      "vezels": "4,8",
      "zout": "0,8"
    }
  ]
}

function loadIngredients() {
  $.each(data.data, function(index) {
    console.log(this.ingredient);
  });
}

loadIngredients();
<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.

1 Comment

Thank you! This works. What if I change my JSON "data": [{ in the top of the script to ingredienten? data.ingredienten nor ingredienten.data seems to work now.

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.