MCPcopy Create free account
hub / github.com/TanStack/query / updateNestedDataByPath

Function updateNestedDataByPath

packages/query-devtools/src/utils.tsx:244–315  ·  view source on GitHub ↗
(
  oldData: unknown,
  updatePath: Array<string>,
  value: unknown,
)

Source from the content-addressed store, hash-verified

242 * @returns A copy of `oldData` with the value at `updatePath` replaced.
243 */
244export const updateNestedDataByPath = (
245 oldData: unknown,
246 updatePath: Array<string>,
247 value: unknown,
248): any => {
249 if (updatePath.length === 0) {
250 return value
251 }
252
253 const type = getNativeObjectType(oldData)
254 if (type === 'Map') {
255 const newData = new Map<unknown, unknown>(
256 Map.prototype.entries.call(oldData),
257 )
258
259 if (updatePath.length === 1) {
260 newData.set(updatePath[0], value)
261 return newData
262 }
263
264 const [head, ...tail] = updatePath
265 newData.set(head, updateNestedDataByPath(newData.get(head), tail, value))
266 return newData
267 }
268
269 if (type === 'Set') {
270 const setAsArray = updateNestedDataByPath(
271 Array.from(Set.prototype.values.call(oldData)),
272 updatePath,
273 value,
274 )
275
276 return new Set(setAsArray)
277 }
278
279 if (Array.isArray(oldData)) {
280 const newData = [...oldData]
281
282 if (updatePath.length === 1) {
283 // @ts-expect-error
284 newData[updatePath[0]] = value
285 return newData
286 }
287
288 const [head, ...tail] = updatePath
289 // @ts-expect-error
290 newData[head] = updateNestedDataByPath(newData[head], tail, value)
291
292 return newData
293 }
294
295 if (isPlainObject(oldData)) {
296 const descriptors = Object.getOwnPropertyDescriptors(oldData)
297 const [head, ...tail] = updatePath
298 if (head === undefined) return oldData
299 const previous = Object.getOwnPropertyDescriptor(oldData, head)
300 if (tail.length && (!previous || !('value' in previous))) return oldData
301 return Object.create(Object.getPrototypeOf(oldData), {

Callers 4

ClearArrayButtonFunction · 0.90
ToggleValueButtonFunction · 0.90
ExplorerFunction · 0.90
utils.test.tsFile · 0.90

Calls 3

getNativeObjectTypeFunction · 0.90
getMethod · 0.80
isPlainObjectFunction · 0.70

Tested by

no test coverage detected