| 237 | * @returns 是否设置成功 |
| 238 | */ |
| 239 | export function setData(data: DataMap, path: string, value: DataValue): boolean { |
| 240 | // 验证路径 |
| 241 | if (!isValidJsonPointer(path)) { |
| 242 | return false; |
| 243 | } |
| 244 | |
| 245 | // 空路径无法设置(需要替换整个对象) |
| 246 | if (path === '') { |
| 247 | return false; |
| 248 | } |
| 249 | |
| 250 | // 解析路径 |
| 251 | const tokens = parseJsonPointer(path); |
| 252 | |
| 253 | if (tokens.length === 0) { |
| 254 | return false; |
| 255 | } |
| 256 | |
| 257 | // 遍历到父节点 |
| 258 | let current: DataValue | undefined = data; |
| 259 | const parentTokens = tokens.slice(0, -1); |
| 260 | const lastToken = tokens[tokens.length - 1]!; |
| 261 | |
| 262 | for (const token of parentTokens) { |
| 263 | if (current === null || current === undefined) { |
| 264 | return false; |
| 265 | } |
| 266 | |
| 267 | // 处理数组 |
| 268 | if (Array.isArray(current)) { |
| 269 | const index = parseInt(token, 10); |
| 270 | if (isNaN(index) || index < 0 || index >= current.length) { |
| 271 | return false; |
| 272 | } |
| 273 | current = current[index] as DataValue | undefined; |
| 274 | } |
| 275 | // 处理对象 |
| 276 | else if (typeof current === 'object') { |
| 277 | const obj = current as DataMap; |
| 278 | if (!(token in obj)) { |
| 279 | // 自动创建中间对象 |
| 280 | obj[token] = {}; |
| 281 | } |
| 282 | current = obj[token]; |
| 283 | } |
| 284 | // 基本类型无法继续遍历 |
| 285 | else { |
| 286 | return false; |
| 287 | } |
| 288 | } |
| 289 | |
| 290 | // 设置值 |
| 291 | if (current === null || current === undefined) { |
| 292 | return false; |
| 293 | } |
| 294 | |
| 295 | // 处理数组 |
| 296 | if (Array.isArray(current)) { |