假设我有一个像这样的对象:
{
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;
};
有任何想法吗?
HUX布斯
相关分类