Home > Net >  How to bypass undefined (reading 'src') using jquery $.each
How to bypass undefined (reading 'src') using jquery $.each

Time:10-07

How do you bypass undefined (reading 'src') within a jquery $.each format.

I have about 100 products that some have images and some don't.

Using jquery $.ajax I am able to get the response. then I use the response in $.each format as per below

 $.each(response, function (i, item) {
    console.log(item);  
    
   var gmi = item.images[0].src; 
    
    
    });

The above code works for products with an image and limit to 1 in the ajax call. However, when I lift the limit and load in all products (including those without images) the same code throws an error and page doesn't build.

Uncaught TypeError: Cannot read properties of undefined (reading 'src')

I've tried the following codes below creating a var to change the src and have even use .lenght to try and by pass it, but had no success.

$.each(response, function (i, item) {
console.log(item);  

if(item.images =="undefined"){
var gmi = "no image applied";} 
else {var gmi = item.images[0].src;}


});

OR

$.each(response, function (i, item) {
console.log(item);  
 
var img = item.images;         
    img.lenght;     
if(img ===0){
var gmi = "no image applied";} 
else {var gmi = item.images[0].src;}


});

In the item array. those products with images have item.images[0].src and those without have item.images, the item.images because it empty is causing my headache.

So is it possible to bypass when the image object has no "src" ?

Kind regrads.

CodePudding user response:

Have a look at optional chaining
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

var gmi = item?.images[0]?.src; 

CodePudding user response:

There is a typo error in the second code. Did you mean?

var img = img.length;
  • Related