Reputation: 2240
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
}
Upvotes: 0
Views: 4389
Reputation: 68393
I have an object that is evaluating as undefined
because data[0]
is undefined
Directly use
if ( Object.keys( data ).length == 0 )
{
do something
}
Upvotes: 4
Reputation: 10682
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
}
Upvotes: 5