假設我有一個像這樣的對象:{ id: 1, name: 'E1', children: [ { id: 2, name: 'E2', children: [ { id: 3, name: 'E3', }, { id: 7, name: 'E7', }, ], }, { id: 4, name: 'E4', children: [ { id: 5, name: 'E5', children: [ { id: 6, name: 'E6', }, ], }, ], }, ],};我想獲取給定路徑的填充了對象數據的樹,例如children.0.children.0應該返回{ id: 1, name: 'E1', children: [ { id: 2, name: 'E2', children: [ { id: 3, name: 'E3', }, ], } ]}我有這樣的東西,但它實際上不起作用:const createPath = (obj, path, value = null) => { let current = obj; while (path.length > 1) { const [head, ...tail] = path; path = tail; if (current[head] === undefined) { current[head] = {}; } current = current[head]; } current[path[0]] = value; return obj;};有任何想法嗎?
根據給定路徑填充JavaScript中對象的所有節點
ABOUTYOU
2023-08-10 10:53:00