根据树节点的位置,修改对应的节点值?

如题,根据树形结构中的节点位置,修改节点的值,例如

[
  {
    id: 0,
    pos: '0',
    name: 'a-0',
    children: [
      {
        id: 1,
        pos: '0-0',
        name: 'b-1'
      },
      {
        id: 2,
        pos: '0-1'
        name: 'b-2',
      },
      {
        id: 3,
        pos: '0-2'
        name: 'b-3',
        children: [
          {
            id: 4,
            pos: '0-2-0'
            name: 'c-4',
          },
          {
            id: 5,
            pos: '0-2-1',
            name: 'c-5',
            children: [
              {
                id: 6,
                pos: '0-2-1-0'
                name: 'd-6',
              }
            ]
          }
        ]
      }
    ]
  }
]

已知位置'0-2-1'表示 'c-5', 可以通过这个位置修改树的值。希望能够通过不递归查询树的方式修改值,可扩展。谢谢

阅读 6.7k
3 个回答

供参考

'0-2-1'.split('-').reduce((node, p, i, pos) => i === pos.length - 1 ? node[p].name : node[p].children, data)

对应的方法:

function setTreeDataByPos(, pos, callback) {
  const posArr = pos.split('-')

  posArr.reduce((node, p, i, pos) => {
    if(i === posArr.length - 1) {
      callback(node, i)
    } else { 
      return node[p].children
    }
  }, tree)
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题