简体   繁体   中英

Object empty check not working in typescript

I try to push the rank value inside the array if it is not empty. But i cannot check the empty value.

Array Data 
0: {name: 0, age: 58, dob: "", mark1: 63, mark2: 43}
1: " "
2: " "
3: " "
4: " "
5: " "
6: " "

if object is empty it should not enter into if loop,right now Loops enter into all the 6 objects.

for (let j = 0; j <= 6; j++) 
    {

        if(rankData[j] !==undefined &&  rankData[j] !==" " &&   (Object.keys(rankData[j]).length)!== 0 &&
        rankData[j] !=='undefined' &&  rankData[j] !=='undefined-undefined' )
        { 
            rankData[j].rank = J;
        }
    }

If object is not empty is should push the rank value . But right now even object is empty it enter into if loop and show error in this line rankData[j].rank = J;

It is necessary to check whether element of an array satisfies the condition. If the condition is satisfied, then assign some value to rank property:

 let arr = [ { name: 0, age: 58, dob: "", mark1: 63, mark2: 43 } , " " , " " , " " , " " , " " , " " ]; for (let index = 0; index < arr.length; index++) { let elem = arr[index]; if (Object.keys(elem).length > 0 && typeof elem != 'string' && elem) { elem.rank = index; console.log(elem); } } console.log(arr);

If you want to check weather some given “something” Is empty you can use this function that I once found on internet.

function isEmpty (value) {
   if (typeof value === “undefined”) return true;
   if (value === null) return true;
   if (typeof value === “string” && value.trim().length === 0) return true;
    if (Array.isArray(value).length === 0) return true;
   if (typeof value === “object” && Object.keys(value).length === 0) return true

  // if none of that is true we return false 
    return false;
}

I think you have used J instead of j (in rankData[j].rank = J;)

 var array = [ {name: 0, dob: ""}, " ", " ", " " ]; for(var j=0; j<=4; j++){ if(array[j] !== undefined && array[j] !== " ") { array[j].rank = j; } } console.log(array);

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