UNPKG

@cmtlyt/cl-utils

Version:
91 lines (90 loc) 3.07 kB
/** * 升级对象 * @param {object} obj */ export function upgradeObj(obj) { const funcMap = { forEach(callback, thisArgs) { const keys = Object.keys(this); keys.forEach(key => { callback.apply(thisArgs || this, [this[key], key, this]); }); }, map(callback, thisArgs) { const keys = Object.keys(this); const list = []; for (let i = 0; i < keys.length; i++) { list.push(callback.apply(thisArgs || this, [this[keys[i]], keys[i], this])); } return list; }, some(callback, thisArgs) { const keys = Object.keys(this); for (let i = 0; i < keys.length; i++) { if (callback.apply(thisArgs || this, [this[keys[i]], keys[i], this])) return true; } return false; }, every(callback, thisArgs) { const keys = Object.keys(this); for (let i = 0; i < keys.length; i++) { if (!callback.apply(thisArgs || this, [this[keys[i]], keys[i], this])) return false; } return true; }, find(callback, thisArgs) { const keys = Object.keys(this); for (let i = 0; i < keys.length; i++) { if (callback.apply(thisArgs || this, [this[keys[i]], keys[i], this])) return this[keys[i]]; } return null; }, filter(callback, thisArgs) { const keys = Object.keys(this); const newObj = {}; for (let i = 0; i < keys.length; i++) { if (callback.apply(thisArgs || this, [this[keys[i]], keys[i], this])) newObj[keys[i]] = this[keys[i]]; } return newObj; }, flat(depth, sep = '.') { const newObj = {}; const flatFunc = (obj, depth, prefix = '') => { for (let key in obj) { if (typeof obj[key] === 'object' && !Array.isArray(obj[key]) && depth > 0) { flatFunc(obj[key], depth - 1, prefix + key + sep); } else { newObj[prefix + key] = obj[key]; } } }; const obj = this; flatFunc(obj, depth); return newObj; }, remove(keys) { if (typeof keys === 'string') { keys = [keys]; } if (!Array.isArray(keys)) { console.error('key必须是字符串数组或字符串'); } return this.filter((_, key) => { return !keys.includes(key); }); }, }; for (let key in funcMap) { Object.defineProperty(obj, key, { value: funcMap[key], writable: false, enumerable: false, configurable: false, }); } }