From 17d3f39917710f4a306bed89b87026382f8cf11d Mon Sep 17 00:00:00 2001 From: sunlizhou <296190577@qq.com> Date: Wed, 29 Nov 2023 17:59:13 +0800 Subject: [PATCH] =?UTF-8?q?=E9=85=8D=E7=BD=AE=E5=88=97=E8=A1=A8=E5=86=85?= =?UTF-8?q?=E5=AE=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/engineer/utils/object.ts | 50 ++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) 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) +}