const getPropByPath1 = (object, path, defaultVal) => {
const _path = Array.isArray(path)
? path
: path.split('.');
if (!_path.length) {
return object === undefined ? defaultVal : object
}
return getPropByPath1(object[_path.shift()], _path, defaultVal)
}
const getPropByPath2 = (obj, path, defaultValue) => {
const travel = regexp =>
String.prototype.split
.call(path, regexp)
.filter(Boolean)
.reduce((res, key) => (res !== null && res !== undefined ? res[key] : res), obj);
const result = travel(/[,[\]]+?/) || travel(/[,[\].]+?/);
return result === undefined || result === obj ? defaultValue : result;
};
const getPropByPath3 = (object, path, defaultValue) => {
const _path = Array.isArray(path)
? path
: path.split('.');
if (object && _path.length) return getPropByPath3(object[_path.shift()], _path, defaultValue);
return object === undefined ? defaultValue : object;
};
const obj = {
mobile: {
aside: true,
isTitle: true,
},
};
const path = 'mobile.isTitle.foo.bar';
const def = 'foo';