@darwish/utils-core
Version:
44 lines (43 loc) • 1.33 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
/* eslint-disable no-param-reassign */
var utils_is_1 = require("@darwish/utils-is");
/**
* @description Get value from object by path.
* @test ✅Tested (已通过测试放心使用)
* @param obj The object to query.
* @param key The key of the property to get.
* @param def The default value.
* @param p The index of the key.
* @param undef The undefined value.
*/
function dlv(obj, key, def, p, undef) {
if (!(0, utils_is_1.isObject)(obj)) {
if (utils_is_1.isDev) {
console.error('obj is not an object');
}
return obj;
}
var keys = [];
if ((0, utils_is_1.isString)(key)) {
keys = key.split ? key.split('.') : [];
}
else if ((0, utils_is_1.isArray)(key)) {
keys = key;
}
var data = Object.assign({}, obj);
for (p = 0; p < keys.length; p++) {
var findKey = keys[p];
data = (0, utils_is_1.isObject)(data) && findKey in data ? data[findKey] : undef;
}
if (data === undef) {
// not exist with default function
if ((0, utils_is_1.isFunction)(def)) {
// not exist with default function and context
return def.call(obj);
}
return def;
}
return data;
}
exports.default = dlv;