Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
130 views
in Technique[技术] by (71.8m points)

javascript - trying to not to iterate on undefined or not available objects

I am trying to add type of material objects to the array using below code but getting an error when one of the object is not available.

and the error is

Unhandled Rejection (TypeError): (intermediate value)(intermediate value)(intermediate value) is not iterable

        constructionSetMasterObject = cloneDeep(data);
        if (!constructionSetMasterObject.glazingOrGasMaterials.length) {
          console.log(constructionSetMasterObject);
          constructionSetMasterObject.glazingOrGasMaterials = [
            ...constructionSetMasterObject?.glazingGasMaterials,  // here i am getting an error 
            ...constructionSetMasterObject?.glazingSimpleMaterials,
            ...constructionSetMasterObject?.glazingComplexMaterials
          ];
          delete constructionSetMasterObject.glazingGasMaterials;
          delete constructionSetMasterObject.glazingSimpleMaterials;
          delete constructionSetMasterObject.glazingComplexMaterials;
          delete constructionSetMasterObject.gasMaterialId;
          delete constructionSetMasterObject.simpleMaterialId;
          delete constructionSetMasterObject.complexMaterialId;
          delete constructionSetMasterObject.opaqueMaterialId;
        }

and i tried the below one but it is not going to work out

...constructionSetMasterObject?.glazingSimpleMaterials ||{}

the object ...constructionSetMasterObject?.glazingGasMaterials is not available and could any one please suggest any efficient way to check that if object is exist only iterate that or any other ways to avoid this situation.

Many thanks in advance

question from:https://stackoverflow.com/questions/65854414/trying-to-not-to-iterate-on-undefined-or-not-available-objects

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The reason that

 [...constructionSetMasterObject?.glazingSimpleMaterials || {}]

Raises that error is because the default value you specified is an object {} which is not iterable.

Instead, the default value specified should be an iterable value, i.e. an empty array ([]).

constructionSetMasterObject.glazingOrGasMaterials = [
    ...constructionSetMasterObject?.glazingGasMaterials ?? [], 
    ...constructionSetMasterObject?.glazingSimpleMaterials ?? [], 
    ...constructionSetMasterObject?.glazingComplexMaterials ?? []
];

Note that I've chosen use the ?? operator above for consistency and symmetry with your existing use of ?. but || would also work just fine.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...