To automatically add properties to an object that is undefined with JavaScript, we can use the hasOwnProperty
method to check if a property exists.
It’ll return true
if it exists and false
otherwise.
If it returns false
, then we can set the property value to the value we want.
For instance, we can write:
const test = {}
if (!test.hasOwnProperty('hello')) {
test.hello = {};
}
test.hello.world = "Hello World!"
We have the test
object that we want to add the hello
property to if it doesn’t exist.
We check that it doesn’t exist with !test.hasOwnProperty(‘hello’)
.
And if that’s true
, we set test.hello
to an empty object.
Then we set test.hello.world
to “Hello World!”
.
The hasOwnProperty
method can be overridden easily since it’s inherited from the Object
constructor.
Therefore to make sure we always call the right hasOwnProperty
method, we can write:
const test = {}
if (!Object.prototype.hasOwnProperty.call(test, 'hello')) {
test.hello = {};
}
test.hello.world = "Hello World!"
We call Object.prototype.hasOwnProperty.call
with test
to do the same thing as test.hasOwnProperty
, but we make sure that we always call the right one from the Object
constructor.