(data: DataValue, path: string)
| 181 | * @returns 路径对应的数据值,如果路径不存在则返回 null |
| 182 | */ |
| 183 | export function getData(data: DataValue, path: string): DataValue | null { |
| 184 | // 验证路径 |
| 185 | if (!isValidJsonPointer(path)) { |
| 186 | return null; |
| 187 | } |
| 188 | |
| 189 | // 空路径返回整个数据 |
| 190 | if (path === '') { |
| 191 | return data; |
| 192 | } |
| 193 | |
| 194 | // 解析路径 |
| 195 | const tokens = parseJsonPointer(path); |
| 196 | |
| 197 | // 遍历路径 |
| 198 | let current: DataValue | undefined = data; |
| 199 | |
| 200 | for (const token of tokens) { |
| 201 | if (current === null || current === undefined) { |
| 202 | return null; |
| 203 | } |
| 204 | |
| 205 | // 处理数组 |
| 206 | if (Array.isArray(current)) { |
| 207 | // 检查是否为有效的数组索引 |
| 208 | const index = parseInt(token, 10); |
| 209 | if (isNaN(index) || index < 0 || index >= current.length) { |
| 210 | return null; |
| 211 | } |
| 212 | current = current[index] as DataValue | undefined; |
| 213 | } |
| 214 | // 处理对象 |
| 215 | else if (typeof current === 'object') { |
| 216 | const obj = current as DataMap; |
| 217 | if (!(token in obj)) { |
| 218 | return null; |
| 219 | } |
| 220 | current = obj[token]; |
| 221 | } |
| 222 | // 基本类型无法继续遍历 |
| 223 | else { |
| 224 | return null; |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | return current ?? null; |
| 229 | } |
| 230 | |
| 231 | /** |
| 232 | * 在数据模型中设置指定路径的数据 |
no test coverage detected