Object.hasOwnProperty multiple levels without error

1k Views Asked by At

I wonder if there is some way to use hasOwnProperty for an object for multiple levels.

To illustrate: I have following object:

var Client = {
    ID: 1,
    Details: {
        Title: 'Dr',
        Sex: 'male'
    }
}

I can now do the following in javascript:

('Title' in Client.Details) -> true

However I cannot! do:

('Street' in Client.Adress)

...yet I must first use an if to not throw an error. Because I might have a large object - I only need to know if there is "Adress" in Client.Details without using prior if statements, any idea if that is possible?

// this is overkill -> (will be many more if-statements for checking a lower level
if('Adress' in Client){
    console.log('Street' in Client.Adress)
} else {
    console.log(false)
}

Example which produces the error:

var Client = {
    ID: 1,
    Details: {
        Title: 'Dr',
        Sex: 'male'
    }
}

// Results in Error:
('Street' in Client.Adress)

// Results in Error:
if('Street' in Client.Adress){}

1

There are 1 best solutions below

4
On BEST ANSWER

You could pass the path of your attributes via a String and use a recursive function to run your object down:

const checkPath = (o, path) => {
  if(path.includes('.')){
    if(o.hasOwnProperty(path.split('.')[0])) return checkPath(o[path.split('.')[0]], path.split('.').slice(1).join('.'));
    else return false
  }else return o.hasOwnProperty(path);
}

And use it like this :

checkPath(Client, 'Details.Title')

Demo:

let Client = {
    ID: 1,
    Details: {
        Title: 'Dr',
        Sex: 'male'
    }
};

const checkPath = (o, path) => {
  if(path.includes('.')){
    if(o.hasOwnProperty(path.split('.')[0])) return checkPath(o[path.split('.')[0]], path.split('.').slice(1).join('.'));
    else return false
  }else return o.hasOwnProperty(path);
}

console.log(checkPath(Client, 'Details.Title'));
console.log(checkPath(Client, 'Test.Title'));


Here's the sexy one-liner:

const checkPath = (o, path) => path.includes('.') ? o.hasOwnProperty(path.split('.')[0]) ? checkPath(o[path.split('.')[0]], path.split('.').slice(1).join('.')) : false : o.hasOwnProperty(path);