So, basically you are trying to create a alternative to _.has
of lodash
, but don'w want to write a thousand lines of code to handle all the possible corner cases. Here is a lighter version of has
I implemented for you, that will not fall if the data is inappropiate (but obviously it is not going to handle as many cases handled in lodash
).
I just simple took 2 inputs (as argument) 1: SOurce, 2: the Path (dot separated string/ keys or array of string), then just iterated through that keys and checked if that key exists or not, if exists, I updated the current source as the value that key contains, and folowed the same process.
Here is a Snippet:
function has(src, path = []) {
let _path = Array.isArray(path) ? path.slice() : (path || '').split('.'),
o = src,
idx = 0;
if (_path.length === 0) {
return false;
}
for (idx = 0; idx < _path.length; idx++) {
const key = _path[idx];
if (o != null && o.hasOwnProperty(key)) {
o = o[key];
} else {
return false;
}
}
return true;
}
const obj1 = {a: {b: {c: {d: {e: {f: {g: { h: 210}}}}}}}};
//you can send the path as a array of sequential keys
console.log(has(obj1, ['a', 'b', 'c', 'd', 'e'])) // valid path
console.log(has(obj1, ['a', 'b', 'c', 'd', 'x', 'y'])) //invalid path
//Or, you can pass the path as a single string
console.log(has(obj1, 'a.b.c.d.e.f.g.h')) // valid path
console.log(has(obj1, 'a.x.y.b.c.d.e.f.g.h')) //invalid path