diff --git a/src/engineer/utils/object.ts b/src/engineer/utils/object.ts index 3e293a7..a3c38f7 100644 --- a/src/engineer/utils/object.ts +++ b/src/engineer/utils/object.ts @@ -22,3 +22,53 @@ export function valueOf(obj: any, key: string) { } return find(obj, key.split('.')) } + +function nextValue(keys: string[]): any { + if (!keys.length) { + return undefined + } + if (Number.isNaN(parseInt(keys[0]))) { + return {} + } + return [] +} + +function set(obj: any, keys: string[], value: any): boolean { + if (!keys.length) { + return false + } + if (obj == null || typeof obj !== 'object') { + return false + } + const key = keys.shift()! + if (!Array.isArray(obj)) { + if (!keys.length) { + obj[key] = value + return true + } + if (obj[key] == null) { + obj[key] = {} // 初始化 + } + return set(obj[key], keys, value) + } + const index = Number.parseInt(key) + if (Number.isNaN(index)) { + return false + } + if (!keys.length) { + obj.splice(index, 1, value) + return true + } + for (let i = obj.length; i <= index; i++) { + if (i < index) { + // obj.push(undefined) + // } else { + obj.push(nextValue(keys)) + } + } + return set(obj[index], keys, value) +} + +export function setValue(obj: any, key: string, value: any): boolean { + return set(obj, key.split('.'), value) +}