0

I'm trying to output the "title", "url", "imageUrl" but it only shows "undefined" or "[object Object]", and I have to solve this

My code should output like this:

<p>The Word</p>
<p>Art</p>
<p>Attaining</p>

Here is my JSON code:

{
    "ebookList":{
        "ebook":[
            {
                "title":"The Word",
                "url":"/products/",
                "imageUrl":"/products/",
                "_id":"1"
            },
            {
                "title":"Art",
                "url":"/products/",
                "imageUrl":"/products/",
                "_id":"2"
            },
            {
                "title":"Attaining",
                "url":"/products/",
                "imageUrl":"/products/",
                "_id":"3"
            }
        ]
    }
}

and my javascript:

function loadBooks() {
    $.getJSON('products/books.json', function (result) {
        $.each(result, function (i, res) {
            alert(res.title);
        });
    });
}
2
  • 2
    $.each(result.ebookList.ebook, function (i, res) { alert(res.title); }); or $.each(result['ebookList']['ebook'], function (i, res) { alert(res.title); }); Commented Mar 19, 2016 at 10:49
  • So, it'll be the same as the other properties. Commented Mar 19, 2016 at 11:09

2 Answers 2

1

The problem is that you do each on result which is the whole table. So your res variable will contain every iteration of ebook and here you have only one. The ebook array does not contain any title attribute (which explains the undefined you get), it only contains objects (3 arrays in that example, that explain the output you have when doing alert(res)), that contain title attributes among others.

So to do what you want, you have to do $.each(result.ebookList.ebook, function (i, res) that will loop through the objects inside the ebook object.

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

Comments

1

To alert the titles use this loop.

for(i=0; i<result.ebookList.ebook.length; i++){
  alert(result.ebookList.ebook[i].title);
}

2 Comments

function loadEbooks() { $.getJSON('products/ebooks.json', function (result) { $.each(result, function (i, res) { for (var j in i) { $('#ebooks .contents').append('<p>' + res['ebook'][j].title + '</p>'); } }); }); } also works but it only show 9 results when I've added my json "ebook"
Withou $.each, my loop does the same in pure JavaScript

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.