import { O_CREAT } from "constants"; const _get: any = function (obj: any, path: any, defaultValue: any) { if (path.substr) path = path.split(/\.|\\|\//); if (path.length && obj) { return _get(obj[path.shift()], path, defaultValue); } else if (!path.length && obj) { return obj; } else { return defaultValue; } }; const _find = function (collection: any, predicate: any) { if (!collection) return undefined; if (typeof predicate === 'string') { for (let item of collection) { if (Object.keys(item).indexOf(predicate) > -1) { return item; } } } else if (predicate instanceof Array && predicate.length === 2) { for (let item of collection) { if (Object.keys(item).indexOf(predicate[0]) > -1 && item[predicate[0]] === predicate[1]) { return item; } } } else if (Object.prototype.toString.call(predicate) === '[object Object]') { for (let item of collection) { let r = true; Object.entries(predicate).map(([key, value]) => { if (item[key] !== value) { r = false; } }); if (r) { return item; } } } else if (Object.prototype.toString.call(predicate) === '[object Function]') { for (let item of collection) { if (predicate(item)) { return item; } } } return undefined; }; // 没有考虑所有情况,只是适用于此 const _groupBy = (arr: any, value: any) => { return arr.reduce((pre: any, cur: any) => { const key = cur[value]; if (pre.hasOwnProperty(key)) { pre[key].push(cur); } else { pre[key] = [cur]; } return pre }, {a:1}) } export default { get: _get, find: _find, groupBy: _groupBy, }