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
}
undefinedornull. Property names are always strings or Symbols. The question is really unclear, please do reply to @mehulmpt's question above.data[0]is indeed undefined. Is checking fordata[0]the only way to find out ifdatadoes not contain any elements? My assumption was that I could doif (Object.keys(data[0]) === null){ do something }dataitself. I did not think to do that because my assumption was that if I am getting a value greater than 0 on the object length, then doing a test on the object itself would not give false.data[0]is indeed undefined" Right, but that's not the property key. That's the property value (or rather, the value you get when the object doesn't have a property by the name you requested). The property key you're checking there is"0". Sincedatadoesn't have a property called"0", you getundefined. Again: Keys cannot beundefined,null, or indeed anything but a string or Symbol.