简体   繁体   中英

Javascript test if object has any keys that are not undefined or null

I have an object that is evaluating as undefined when I try to read its keys using Object.keys(). However, when I do Object.keys().length I get 1.

How can I test an object for presence if any key other than undefined or null.

I've tried the following, but still get errors. I'm essentially just checking the first element to see if it is null or undefined. I'm guessing there may be a better way to run this kind of check.

I've googled and seen cases of handling a search for a specific property, but that is not how my object is setup. I actually have an object with nested objects. Player1 and Player2 can be any value.

var data =
    { 
      player1:
       { team: team1,
         score: 6 },
      player2:
       { team: team2,
         score: 4} 
    }

Here is what my object can also look like and it is causing undefined to be displayed when I attempt to loop through and display it in a table.

{ undefined:
   { team: undefined,
     score: '0'} }

As you can see doing a length check will return 1. So I'm guessing I have to check for the first elemnent data[0] ? That check works, but is that the best way to handle this?

if (Object.keys(data[0]) === null){
do something
}
if (Object.keys(data).length === 0){
    // There are no keys
}

Also check that data itself isn't null or undefined .

if (!data || typeof data !== "object" || Object.keys(data).length === 0) {
    // This is either a null, undefined, not an object, or an object with no keys
}

I have an object that is evaluating as undefined

because data[0] is undefined

Directly use

if ( Object.keys( data ).length == 0 )
{
   do something
}

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