1

Say I have this object:

myObj = {
    level1: {
        level2: {
            name: 'Frank'
        }
    }
};

How can I use hasOwnProperty() to check multiple depths of my object. Something like this works:

if (myObj.hasOwnProperty('level1') {
    if (myObj.hasOwnProperty('level2') {
        if (myObj.hasOwnProperty('name') {
            console.log(myObj.level1.level2.name)
        }
    }
}

I was hoping for something like:

myObj.hasOwnProperty(['level1', 'level2', 'name']);
myObj.hasOwnProperty('level1.level2.name);

My goal is to not console.log(myObj.level1.level2.name) if not all the properties are there, so you can answer this question by providing an alternate for hasOwnProperty also.

Freddy Bonda
  • 1,189
  • 6
  • 15
  • 33

1 Answers1

6

You could take a closure over the object and check the keys.

const check = o => k => [o.hasOwnProperty(k), o = (o || {})[k]][0];

var myObj = { level1: { level2: { name: 'Frank' } } };

console.log(['level1', 'level2', 'name'].every(check(myObj)));
console.log(['level1', 'level3', 'name'].every(check(myObj)));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392