UNPKG

muz-doraemon

Version:

自主开发的UniApp组件——Жидзин(Zidjin)系列组件库。

52 lines (41 loc) 1.77 kB
// import { isArr, isObj, isNum, isStr, isUndef } from './assert.js'; const takeType = data => Object.prototype.toString.call(data).slice(8, -1); const isArr = data => takeType(data) === 'Array'; const isObj = data => takeType(data) === 'Object'; const isNum = data => typeof data === 'number'; const isStr = data => typeof data === 'string'; const isUndef = data => ['', null, undefined].includes(data); const XTakeAt = {}; /** * Object takes value by path * @function get * @param {Record<string, any> | any[]} source * @param {String} path 指定的查询路径,支持.操作符,支持数组下标[i] * @param {any} defaultValue 返回的默认值, 非必传 * @returns * @author SevenDream Yang * @demo * let obj = {a: 'aaa', b: { c: 'ccc', d: ['d1', 'd2']}}; * let val = XTakeAt.getValue(obj, 'b.d[0]', ) * 返回 => 'd1' */ XTakeAt.getValue = function (source, path, defaultValue = undefined) { let target = source; let handlePath = path; // 如果是数字则转换为字符串 if (isNum(path)) handlePath = isNaN(path) ? '' : path.toString(); // 如果路径不是字符串则返回默认值 if (!isStr(handlePath)) return defaultValue; // 判断是不是对象或数组,如果都不是就返回目标对象 if (!isObj(source) && !isArr(source)) return source; // 将路径格式转数组 const routes = handlePath.replace(/(\[|\])/g, a => (a === '[' ? '.' : '')).split('.'); // 返回取得的结果 for (let i = 0, len = routes.length; i < len; i++) { const field = routes[i]; if (isUndef(target[field])) return (target = defaultValue); target = target[field]; } return target; }; export default XTakeAt;