如何跳过键值对中的 undefined/missing 个值

How to skip undefined/missing values in key-value pairs

我正在尝试从 API 中的 json 构建一个引文生成器,其中包含有关图像的数据,存储在键值对中。我可以将 return 的数据显示到屏幕上,但它总是在引用中包含 undefined 。 Sample manifest return 未定义为创建者,因为此特定记录中未列出。如何防止任何未定义的值被 returned?我试过将 forEach 更改为映射,按字符串长度过滤 allMetadata,在 insertCitation 处使用 if !== undefined,以及代码中不同位置的那些版本。

编辑:已更新以提供完整代码,包括打印到页面

(function () {
'use strict';

const buildCitation = {
    buildMetadataObject: async function (collAlias, itemID) {
        let response = await fetch('/iiif/info/' + collAlias + '/' + itemID + '/manifest.json');
        let data = await response.json()
        let allMetadata = data.metadata
        let citationData = {};
        allMetadata.forEach(function (kvpair) {
            if (kvpair.value == undefined) {
                return false;
            } else if (kvpair.label === 'Title') {
                citationData.itemTitle = kvpair.value;
            } else if (kvpair.label === 'Creator') {
                citationData.itemCreator = kvpair.value;
            } else if (kvpair.label === 'Repository') {
                citationData.itemRepository = kvpair.value;
            } else if (kvpair.label === 'Collection Name') {
                citationData.itemCollection = kvpair.value;
            } else if (kvpair.label === 'Owning Institution') {
                citationData.itemOwning = kvpair.value;
            } else if (kvpair.label === 'Date') {
                citationData.itemDate = kvpair.value;
            } else if (kvpair.label === 'Storage Location') {
                citationData.itemStorage = kvpair.value;
            }
        return true;
        });
        return citationData;
    },
    insertCitation: function (data) {
        var testTitle = data.itemTitle;
        console.log(testTitle);
        const itemCite = `Citation: "${data.itemTitle}," ${data.itemDate}, ${data.itemCreator}, ${data.itemCollection}, ${data.itemOwning}, ${data.itemStorage}, ${data.itemRepository}.`;
        const citationContainer = document.createElement('div');
        citationContainer.id = 'citation';
        citationContainer.innerHTML = itemCite;

        // CHANGED to innerHTML instead of innerText because you may want to format it at some point as HTML code.

        if (testTitle) {
            document.querySelector('.ItemView-itemViewContainer').appendChild(citationContainer);
        }
    }
}

document.addEventListener('cdm-item-page:ready', async function (e) {
    const citationData = await buildCitation.buildMetadataObject(e.detail.collectionId, e.detail.itemId);
    console.log({ citationData });
    buildCitation.insertCitation(citationData);
});

document.addEventListener('cdm-item-page:update', async function (e) {
    document.getElementById('citation').remove();
    const citationData = await buildCitation.buildMetadataObject(e.detail.collectionId, e.detail.itemId);
    console.log({ citationData });
    buildCitation.insertCitation(citationData);
});

})();

我已经简化了你的程序。未定义是因为没有带有标签 Date

的项目

const mappings = {
  Date: 'itemDate',
  Title: 'itemTitle',
  Creator: 'itemCreator',
  Repository: 'itemRepository',
  'Storage Location': 'itemStorage',
  'Owning Institution': 'itemOwning',
  'Collection Name': 'itemCollection',
}
async function buildMetadataObject(collAlias, itemID) {
  let response = await fetch('https://teva.contentdm.oclc.org/iiif/info/p15138coll25/1421/manifest.json');
  let data = await response.json()
  return data.metadata.reduce(
    (acc, { label, value }) => ({ ...acc, [ mappings[label] ]: value }),
    {}
  )
}

function insertCitation(data) {
  var testTitle = data.itemTitle;
  const fieldBlackList = ['itemTitle'];
  const itemCite = `Citation: "${data.itemTitle}," ${
    Object.values(mappings).reduce((acc, cur) => {
      if (fieldBlackList.includes(cur)) return acc;
      const value = data[cur]; 
      return value ? [...acc, value] : acc 
    }, []).join(', ')
  }.`;
  console.log(itemCite);
}
//MAIN PROGRAM
(async() => {
  const citationData = await buildMetadataObject();
  insertCitation(citationData);
})()