I'm working with two objects in JS and I need to know if a given subobject exists. My objects look something like this:
obj1 = {
sobj1: 1234,
sobj2: {
ssobj1: "abc",
ssobj2: 1234
}
}
The catch is that I don't know beforehand the exact shape of the object and when I try to check if ssojb1
exists with an if (obj1.sobj2.ssobj1)
and sobj2
isn't set, I'll get an error like "trying to read property ssobj1
of undefined
.
To circumvent this, my approach was to use a cascade of if
statements, but I'm pretty sure that there's a better option. This can get ugly pretty quickly.
Any suggestions?