javascripteuropeana-api

How to retrieve specific properties from an API only if certain conditions are met, i.e. if the properties exist?


I am using Europeana API to populate my website with certain photographs. I have decided which metadata I would like to retrieve but I ran into a problem when I realized that not all the photographs have the metadata that I want and that leads to errors and undefined.

How can I condition it so that e.g. edmPlaceLabel is shown only if it exists for the photo that is being retrieved? If it doesn't exist, simply skip it and move on.

data.items.forEach((item) => {
    const output = document.querySelector('#output');
    const title = item.title,
        year = item.year,
        provider = item.provider,
        dataProvider = item.dataProvider,
        LabelLangAware = item.edmConceptPrefLabelLangAware,
        edmPlaceLabel = item.edmPlaceLabel[0],
        edmPlaceLabelLangAware = item.edmPlaceLabelLangAware.hr[0],
        edmTimespanLabel = item.edmTimespanLabel[30].def,
        edmTimespanLabelLangAware = item.edmTimespanLabelLangAware.hr,
        europeanaCollectionName = item.europeanaCollectionName[0],
        link = item.guid,
        thumbnail = item.edmPreview[0],
        edmIsShownBy = item.edmIsShownBy;

    output.innerHTML += `${index}
        <a href="${link}">Link: ${title}</a>
        <br>
        <h4>${title}</h4>
        <p>Godina: ${year}</p>
        <p>Izvor: ${dataProvider}</p>
        <p>Opis: ${LabelLangAware}</p>
        <p>Mjesto: ${edmPlaceLabel}</p>
        <p>Mjesto: ${edmPlaceLabelLangAware}</p>
        <p>${edmTimespanLabel}</p>
        <p>${edmTimespanLabelLangAware}</p>
        <p>Provider: ${provider}</p>
        <p>Kolekcija: ${europeanaCollectionName}</p>
        <br>
        <img src="${thumbnail}" alt="${title}">
        <br>
        <p>Link na izvor: ${edmIsShownBy}</p>
        `;
});

Solution

  • Try using ternary expression

    Example:

    var val = obj ? obj.prop : '';
    

    is the same as:

    var val = null;
    
    if (obj) {
        val = obj.prop;
    } else {
        val = ''
    }
    

    Can also be used with string variables:

    `hello ${val ? val : ''} world`