简体   繁体   中英

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

I am trying to add the id's to array if those are available like as below

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

I am calling above function in other place like as below

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 undefined

Could any one please suggest any ideas or alternative approaches on this that would be very grateful to me, many thanks in advance.

Try like below

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

It needs to filter the array after push all values.

Also you can simplify the code by simple remove the push calls

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

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