如何仅在满足特定条件(即属性存在时)的情况下从 API 检索特定属性?

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

我正在使用 Europeana API 用某些照片填充我的网站。我已经决定要检索哪些元数据,但是当我意识到并非所有照片都具有我想要的元数据并导致错误和未定义时,我 运行 遇到了问题。

我怎样才能调整它,例如edmPlaceLabel 仅当它存在于正在检索的照片时才会显示?如果它不存在,只需跳过它并继续。

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

尝试使用 ternary expression

示例:

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

等同于:

var val = null;

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

也可以与字符串变量一起使用:

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