简体   繁体   中英

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 eg 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>
        `;
});

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`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM