UNPKG

xe-utils

Version:

JavaScript 函数库、工具类

53 lines (48 loc) • 1.77 kB
import hasOwnProp from './hasOwnProp.js';import isUndefined from './isUndefined.js';import eqNull from './eqNull.js';import isString from './isString.js';import helperParsePath from './helperParsePath.js';import helperStringIndexOf from './helperStringIndexOf.js';import staticParsePathNames from './staticParsePathNames.js';import staticParsePathIdxs from './staticParsePathIdxs.js';function getValueByPath (obj, property) { if (!obj) { return } var val = obj[property] if (val || hasOwnProp(obj, property)) { return val } // 快路径:仅「字符串 + 非空 + 不含 '.' + 不含 '['」 if (property && isString(property) && helperStringIndexOf(property, '.') === -1 && helperStringIndexOf(property, '[') === -1) { return } var len = helperParsePath(property) if (!len) return var rest = obj for (var index = 0; index < len; index++) { var key = staticParsePathNames[index] var idx = staticParsePathIdxs[index] var child if (key === null) { child = rest[idx] } else if (idx === -1) { child = rest[key] } else { child = rest[key] ? rest[key][idx] : undefined } if (eqNull(child)) { return index === len - 1 ? child : undefined } rest = child } return rest } /** * 获取对象的属性的值,如果值为 undefined,则返回默认值 * @param {Object/Array} obj 对象 * @param {String/Function} property 键、路径 * @param {Object} defaultValue 默认值 * @return {Object} */ function get (obj, property, defaultValue) { if (eqNull(obj)) { return defaultValue } var result = getValueByPath(obj, property) return isUndefined(result) ? defaultValue : result } export default get