@darwish/utils-core
Version:
41 lines (40 loc) • 1.19 kB
JavaScript
/* eslint-disable no-param-reassign */
import { isArray, isDev, isFunction, isObject, isString, } from '@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.
*/
export default function dlv(obj, key, def, p, undef) {
if (!isObject(obj)) {
if (isDev) {
console.error('obj is not an object');
}
return obj;
}
var keys = [];
if (isString(key)) {
keys = key.split ? key.split('.') : [];
}
else if (isArray(key)) {
keys = key;
}
var data = Object.assign({}, obj);
for (p = 0; p < keys.length; p++) {
var findKey = keys[p];
data = isObject(data) && findKey in data ? data[findKey] : undef;
}
if (data === undef) {
// not exist with default function
if (isFunction(def)) {
// not exist with default function and context
return def.call(obj);
}
return def;
}
return data;
}