繁体   English   中英

如果所有 id 都未定义,则将不同的 id 推送到数组并获取一个数组

[英]pushing different ids to array and getting an array if all id's are undefined

我正在尝试将 id 添加到数组中,如果它们可用,如下所示

export const extractOpaqueConstructionType = library => {
  const opaqueConstructionSecondaryIds= [];
  opaqueConstructionSecondaryIds.push(library?.exteriorWallId);
  opaqueConstructionSecondaryIds.push(library?.exteriorFloorId);
  opaqueConstructionSecondaryIds.push(library?.roofId);
  opaqueConstructionSecondaryIds.push(library?.interiorWallId);
  opaqueConstructionSecondaryIds.push(library?.interiorFloorId);
  opaqueConstructionSecondaryIds.push(library?.belowGradeWallId);
  opaqueConstructionSecondaryIds.push(library?.slabOnGradeId);
  return { opaqueConstructions: opaqueConstructionSecondaryIds || null };
};

我在其他地方调用 function 上方,如下所示

extractSecondaryIds: library => {
    const secondaryIds = {
      ...extractSourceOfData(library),
      ...extractOpaqueConstructionType(library), // this is where i am calling above function
      ...extractGlazingConstructionType(library)
    };
    return secondaryIds;
  },

if all the above id's for example(exteriorWallId, exteriorFloorId, etc...) are undefined, I am getting output from the above function ( extractOpaqueConstructionType ) like opaqueConstructions: [null] where as I am expecting like this opaqueConstructions: null if id's are不明确的

任何人都可以就此提出任何想法或替代方法,非常感谢我,非常感谢。

尝试如下

export const extractOpaqueConstructionType = library => {
const opaqueConstructionSecondaryIds= [
library?.exteriorWallId
library?.exteriorFloorId,
library?.roofId,
library?.interiorWallId,
library?.interiorFloorId,
library?.belowGradeWallId,
library?.slabOnGradeId,
].filter(keyValue => keyValue!==undefine);

return { opaqueConstructions:opaqueConstructionSecondaryIds.length? 
opaqueConstructionSecondaryIds : null };
};

它需要在推送所有值后过滤数组。

您还可以通过简单地删除推送调用来简化代码

export const extractOpaqueConstructionType = library => {
  const opaqueConstructions = [
    library?.exteriorWallId,
    library?.exteriorFloorId,
    library?.roofId,
    library?.interiorWallId,
    library?.interiorFloorId,
    library?.belowGradeWallId,
    library?.slabOnGradeId,
  ].filter(it => it !== null);

  return { opaqueConstructions: opaqueConstructions.length ? opaqueConstructions : null };
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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