首页 > 解决方案 > 检查数组中包含的所有接口是否具有所有字段 - Angular 8

问题描述

我刚刚创建了一组类型化接口。
鉴于某些接口字段是可选的,我很好奇是否有一种智能方法来检查数组中包含的所有接口是否都已填充字段。
这是我的界面:

export interface BibliographicCitation {
  authors?: HTMLCollectionOf<Element>;
  title: string;
  date?: Element;
}

这就是我填充数组的方式:

编辑

citations.forEach(citation => {
    if (citation.getElementsByTagName('author').length === 0 &&
        citation.getElementsByTagName('title').length === 0 &&
        citation.getElementsByTagName('date').length === 0) {

        const interfacedCitation: BibliographicCitation = {
           title: citation.textContent.replace(/\s+/g, ' '),
        };

        if (!bibliographicCitations.includes(interfacedCitation)) { 
            bibliographicCitations.push(interfacedCitation); 
        }
    } 
    else {
        const interfacedCitation: BibliographicCitation = {
           authors: citation.getElementsByTagName('author'),
           title: String(citation.getElementsByTagName('title')[0]).replace(/\s+/g, ' '),
           date: citation.getElementsByTagName('date')[0],
        };

        if (!bibliographicCitations.includes(interfacedCitation)) { 
           bibliographicCitations.push(interfacedCitation); 
        }
    }
});

最后,如何检查输入的所有接口是否都有填写的字段?

标签: javascriptangulartypescriptangular8

解决方案


也许只是使用变量isAllProperties并检查:

let isAllProperties = false;
if (citation.getElementsByTagName('author').length === 0 &&
    citation.getElementsByTagName('title').length === 0 &&
    citation.getElementsByTagName('date').length === 0) {
    // ...
    isAllProperties = true;
} else {

}

if (isAllProperties ) {
    // ...
}

更新:

let isAllProperties = [];
citations.forEach(citation => {
if (citation.getElementsByTagName('author').length === 0 &&
    citation.getElementsByTagName('title').length === 0 &&
    citation.getElementsByTagName('date').length === 0) {

    const interfacedCitation: BibliographicCitation = {
       title: citation.textContent.replace(/\s+/g, ' '),
    };

    if (!bibliographicCitations.includes(interfacedCitation)) { 
        bibliographicCitations.push(interfacedCitation); 
    }
    isAllProperties.push({isAll: true, interfacedCitation});
} 
else {
    const interfacedCitation: BibliographicCitation = {
       authors: citation.getElementsByTagName('author'),
       title: String(citation.getElementsByTagName('title')[0]).replace(/\s+/g, ' '),
       date: citation.getElementsByTagName('date')[0],
    };

    if (!bibliographicCitations.includes(interfacedCitation)) { 
       bibliographicCitations.push(interfacedCitation); 
    }

    isAllProperties.push({isAll: false, interfacedCitation});
}

});


推荐阅读