Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - check for object is undefined works only on first array item

I'm trying to check if the object properties 'compliancestatus' and 'comments' are empty, undefined, undeclared i.e. no real value.

I am first checking that the item exists in the object array and my console.log shows that the values do exist and that both object properties are undefined.

The issue is that the second object triggers the else (obj array after2) somehow...

My object is created using:

// Create the object.
let contentObj = new Object();
contentObj.prefix = clausePrefix;
contentObj.no = clauseNo;

    if (clauseComplianceStatus != null) {
        contentObj.compliancestatus = clauseComplianceStatus;
    }

    if (clauseComments != null) {
        contentObj.comments = clauseComments;
    }

code

        // Check if current iteration exists in the content array.
        if (content.some(e => e.prefix === tempOBJ.content[y].prefix && e.no === tempOBJ.content[y].no)) {
            // THIS WORKS FOR ALL OBJECTS
            let currentIterationIndexOfClauseNo = content.findIndex(e => e.prefix === tempOBJ.content[y].prefix && e.no === tempOBJ.content[y].no);

            if (!content[currentIterationIndexOfClauseNo].compliancestatus && !content[currentIterationIndexOfClauseNo].comments) {
                // THIS WILL ONLY WORK FOR THE FIRST OBJECT
            } else {
                // SECOND OBJECT EXECUTES HERE FOR SOME REASONS DESPITE HAVING BOTH VALUES 'undefined' THE SAME AS THE FIRST OBJECT.
            }
        }
question from:https://stackoverflow.com/questions/65642663/check-for-object-is-undefined-works-only-on-first-array-item

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

1 Reply

0 votes
by (71.8m points)

I can't comment, so I'll have to ask this way. Have you checked if your currentIterationIndexOfClauseNo actually changes? The code is still a little bit hard to understand, but I have one small suggestion to make (no solution but makes the code a bit simpler). Are the values of the first object also both undefined?

const obj = content.find(e => e.prefix === tempOBJ.content[y].prefix && e.no === tempOBJ.content[y].no); // will be undefined if nothing was found
if (obj !== undefined) {
        if (!obj.compliancestatus && !obj.comments) {
            // THIS WILL ONLY WORK FOR THE FIRST OBJECT
        } else {
            // SECOND OBJECT EXECUTES HERE FOR SOME REASONS DESPITE HAVING BOTH VALUES 'undefined' THE SAME AS THE FIRST OBJECT.
        }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...