I think a loop where you keep going deeper into object property should fix this right?
function hasPath(obj, path) {
let copyObj = obj;
return path.split('.').every(key => {
if (
copyObj &&
typeof copyObj === 'object' &&
Object.prototype.hasOwnProperty.call(copyObj, key)
&& copyObj[key]
) {
copyObj = copyObj[key]; // go deeper, even if null/undefined
return true;
}
return false;
});
}
// Example
const testObj = {
name: { first: 'testing' },
age: 30,
phone: null
};
const array = ['name.first', 'name.last', 'age', 'phone', 'address.street'];
array.forEach(keyPath => {
console.log(keyPath, hasPath(testObj, keyPath));
});