为了账号安全,请及时绑定邮箱和手机立即绑定

根据给定路径填充JavaScript中对象的所有节点

根据给定路径填充JavaScript中对象的所有节点

ABOUTYOU 2023-08-10 10:53:00
假设我有一个像这样的对象:{  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;};有任何想法吗?
查看完整描述

1 回答

?
HUX布斯

TA贡献1876条经验 获得超6个赞

这可能是一个解决方案,但它并不能涵盖所有场景,只是一条快乐的道路。我不知道哪些是预期的场景。


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;

}


查看完整回答
反对 回复 2023-08-10
  • 1 回答
  • 0 关注
  • 71 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信