UNPKG

@re-flex/object-path

Version:

Re-flex UTILS _> object-path

71 lines (70 loc) 1.99 kB
class ObjectPath { constructor(source) { this.source = source; } parsingKey(path) { return path .split(".") .map((i) => (!Number.isNaN(Number(i)) ? Number(i) : i)); } get(path) { if (!path) return this.source; const keys = this.parsingKey(path); return keys.reduce((value, currentKey, index, keysArr) => { if (value === undefined || (value === null || value === void 0 ? void 0 : value[currentKey]) === undefined) { keysArr = []; return undefined; } else { value = value[currentKey]; return value; } }, this.source); } set(path, value, creatable = true) { if (path.length === 0) return; const keys = this.parsingKey(path); let _obj = this.source; keys.reduce((acc, key, index) => { if (index === keys.length - 1) { acc[key] = value; return true; } if (acc[key] === undefined && creatable) { acc[key] = {}; } return acc[key]; }, _obj); } push(path, value) { let gettingData = this.get(path); if (Array.isArray(gettingData)) { gettingData.push(value); this.set(path, gettingData); return true; } else { return false; } } del(path) { if (path.length === 0) return false; const keys = this.parsingKey(path); let _obj = this.source; keys.reduce((acc, key, index) => { if (index === keys.length - 1) { delete acc[key]; return true; } return acc[key]; }, _obj); return false; } has(path) { return this.get(path) !== undefined; } } export default ObjectPath;