ABOUTYOU
2023-08-10 10:53:00
假設(shè)我有一個(gè)像這樣的對(duì)象:{ 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', }, ], }, ], }, ],};我想獲取給定路徑的填充了對(duì)象數(shù)據(jù)的樹,例如children.0.children.0應(yīng)該返回{ id: 1, name: 'E1', children: [ { id: 2, name: 'E2', children: [ { id: 3, name: 'E3', }, ], } ]}我有這樣的東西,但它實(shí)際上不起作用: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;};有任何想法嗎?
1 回答

HUX布斯
TA貢獻(xiàn)1876條經(jīng)驗(yàn) 獲得超6個(gè)贊
這可能是一個(gè)解決方案,但它并不能涵蓋所有場景,只是一條快樂的道路。我不知道哪些是預(yù)期的場景。
function createPath(obj, path) {
var newObject = Object.assign({}, obj);
var aux;
var keys = path.split('.');
var i = 0;
while(i < keys.length) {
if (aux) {
aux[keys[i]] = [aux[keys[i]][keys[i+1]]];
aux = aux[keys[i]][keys[i+1]];
} else {
aux = obj[keys[i]][keys[i+1]];
newObject[keys[i]] = [aux];
}
i = i + 2;
}
return newObject;
}
添加回答
舉報(bào)
0/150
提交
取消