aeran
aeran

Reputation: 1397

Uncaught type error on json objects

I kept getting this error (Uncaught TypeError: Cannot read property 'coversrc' of undefined) in the browser

My script as below:

var jsondata = '{"089d89f69b11a9b0a2c8dc156c356f48":{"rowid":"089d89f69b11a9b0a2c8dc156c356f48","id":"978-967-366-281-4","qty":"4","price":"14.40","options":{"coversrc":"\/images\/sized\/images\/uploads\/books\/Apa_Salah_Syiah_Final_CO-80x123.jpg"},"name":"Apa Salah Syiah","subtotal":57.6},"8b0a29a20d0bf409143f07735be32db2":{"rowid":"8b0a29a20d0bf409143f07735be32db2","id":"978-967-408-237-6","qty":"2","price":"23.40","options":{"coversrc":"\/images\/sized\/images\/uploads\/books\/perang-salib2_4-80x124.jpg"},"name":"Perang Salib Kedua","subtotal":46.8},"6ff46686900b2f7c0be05fdc468e78c2":{"rowid":"6ff46686900b2f7c0be05fdc468e78c2","id":"978-967-369-236-1","qty":"1","price":"24.00","options":{"coversrc":"\/images\/sized\/images\/uploads\/books\/Unfair-80x121.jpg"},"name":"Unfair Advantage Edisi Bahasa Melayu","subtotal":24},"total":"128.40","checkout_link":"http:\/\/bookcafe.com.my?dispatch=checkout.remote_add.978-967-366-281-4@4|978-967-408-237-6@2|978-967-369-236-1@1"}';
var myData = JSON.parse(jsondata);

var $grouplist = $('#bookcart');
$.each(myData, function() {
 $('<li>' + this.options.coversrc + '</li>').appendTo($grouplist); // browser error points to here
});

Upvotes: 0

Views: 30

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388316

there are properties like total and checkout_link which does not have the option property.

So inside your loop, check whether the property exists

var $grouplist = $('#bookcart');
$.each(myData, function () {
    if (this.options) {
        $('<li>' + this.options.coversrc + '</li>').appendTo($grouplist); // browser error points to here
    }
});

Demo: Fiddle

Upvotes: 2

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382092

Some of the properties of your object aren't objects (checkout_link, total).

You could do this :

$.each(myData, function() {
  if (!this.options) return;
  $('<li>' + this.options.coversrc + '</li>').appendTo($grouplist); 
});

Upvotes: 2

Related Questions