简体   繁体   中英

JavaScript proper way to handle null in JSON object

Here is the code :

for (i = 0; i < data.RecruitingGroups.length; i++) {
        data.RecruitingGroups[i].id = i;

        if (data.RecruitingGroups[i].Rule.Rules != null) {
            for (j = 0; j < data.RecruitingGroups[i].Rule.Rules.length; i++) {
                data.RecruitingGroups[i].Rule.Rules[j].id = j;
            }    
        } 
    }

Problem is that sometimes RecruitingGroups[].Rule is null. So I tried to verify it was not null before continuing and running the next for loop, but it still throws the error:

Uncaught TypeError: Cannot read property 'Rules' of null

How can i bypass this error.

You're testing if Rule.Rules is null . That's not the problem; Rule itself is null , as evidenced by the error message. You need to test both Rule and Rule.Rules if either can be null.

Try

if (data.RecruitingGroups[i].Rule && data.RecruitingGroups[i].Rule.Rules) {

your second loop needs to increment j++ not i++ . =)

 if (data.RecruitingGroups[i].Rule && data.RecruitingGroups[i].Rule.Rules) {
        for (j = 0; j < data.RecruitingGroups[i].Rule.Rules.length; i++) {
            data.RecruitingGroups[i].Rule.Rules[j].id = j;
        }    
    } 

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