Access Data In Json Not Getting The Key
Solution 1:
I understand that it only appears when there is not property
break_timein
but it is there its justnull
You drew the wrong conclusion here. The error doesn't have anything to do with whether a property exists or not.
When a property doesn't exist and you are trying to access a property on it you are getting the following error:
var foo = {};
foo.bar.baz;
// Uncaught TypeError: Cannot read property 'baz' of undefined
The "undefined" in this sentence doesn't refer to the existence of the property, it refers to the valueundefined
. In JavaScript, when accessing a property doesn't exist, accessing it will return the value undefined
:
foo.bar
// undefined
There are other situations where undefined
is created, e.g. when you define a variable without an initial value:
var abc;
abc;
// undefined
Knowing that we can test what happens when we directly access a property on undefined
:
undefined.foo// Uncaught TypeError: Cannot read property 'foo' of undefined
This throws the same error as above, so it doesn't have anything to do with property access.
So now we have established that undefined
cannot be used in a property access context.
null
is another value that is just like that:
null.foo
// Uncaught TypeError: Cannot read property 'foo' of null
What makes null
and undefined
different from other primitive values (string, number, boolean) that they show this behavior?
null
and undefined
are actually values of two unique data types: Null and Undefined.
Those data types do not have an object wrapper. Strings, Numbers and Boolean values can exist in two forms: as primitive values and as object value:
var primitive = "foo";
varobject = newString("foo");
When you are accessing a property on a primitive value, e.g. "foo".length
, JavaScript automatically converts the primitive value to a temporary object value, similar to new String("foo").length
.
But since there is no object equivalent for Nulland Undefined
(evident by the fact that there is no Null
or Undefined
function), this cannot be done, so an error is thrown.
Solution 2:
Here, null
doesn't have any properties eg- length that's why it's throwing an error saying "Cannot read property 'length' of null"
. You should write the statement like this:
console.log(data[0].break_timein != null || data[0].break_timein.length > 0);
Post a Comment for "Access Data In Json Not Getting The Key"