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

假设我有一个像这样的对象:


{

  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;

};

有任何想法吗?


ABOUTYOU
浏览 110回答 1
1回答

HUX布斯

这可能是一个解决方案,但它并不能涵盖所有场景,只是一条快乐的道路。我不知道哪些是预期的场景。function createPath(obj, path) {&nbsp; var newObject = Object.assign({}, obj);&nbsp; var aux;&nbsp; var keys = path.split('.');&nbsp; var i = 0;&nbsp; while(i < keys.length) {&nbsp; &nbsp; if (aux) {&nbsp; &nbsp; &nbsp; aux[keys[i]] = [aux[keys[i]][keys[i+1]]];&nbsp; &nbsp; &nbsp; aux = aux[keys[i]][keys[i+1]];&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; aux = obj[keys[i]][keys[i+1]];&nbsp; &nbsp; &nbsp; newObject[keys[i]] = [aux];&nbsp; &nbsp; }&nbsp; &nbsp; i = i + 2;&nbsp; }&nbsp;&nbsp;&nbsp; return newObject;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript