UNPKG

web-ui-pack

Version:
65 lines (64 loc) 1.88 kB
const nestedProperty = { parsePath(path) { const keys = []; const isArray = []; let start = 0; for (let i = 0; i < path.length; i++) { const c = path[i]; const isNextArr = c === "["; if (isNextArr || c === ".") { if (i > start) { keys.push(path.substring(start, i)); isArray.push(isNextArr); } if (isNextArr) { const close = path.indexOf("]", i); keys.push(path.substring(i + 1, close)); isArray.push(false); i = close; } start = i + 1; } } if (start < path.length) { keys.push(path.substring(start)); isArray.push(false); } return [keys, isArray]; }, set(obj, path, value) { if (!path) { return obj; } const result = obj; const [propKeys, isArray] = nestedProperty.parsePath(path); let key = propKeys[0]; for (let i = 0; i < propKeys.length - 1; key = propKeys[++i]) { if (!obj[key]) { obj[key] = (isArray[i] ? [] : {}); } obj = obj[key]; } obj[key] = value; return result; }, get(obj, path, out) { if (!path) { return undefined; } const [propKeys] = nestedProperty.parsePath(path); let next = obj; for (let i = 0; i < propKeys.length; ++i) { if (next == null) { break; } const key = propKeys[i]; if (out != null) { out.hasProp = key in next; } next = next[key]; } return next; }, }; export default nestedProperty;