使用 Lodash 实现递归映射

3
我有一段需要递归的数据,但我不知道如何实现。以下是我的数据。 enter image description here 我只需要让它看起来像这样。
[
      {
        id: 1,
        label: 'Satisfied customers',
        children: [
          {
            id: 2,
            label: 'Good food',
            icon: 'restaurant_menu',
            children: [

              { id: 3, label: 'Quality ingredients'},
              { id: 4, label: 'Good recipe' }
            ]
          },
          {
            id: 5,
            label: 'Good service',
            icon: 'room_service',
            children: [
              { id: 6, label: 'Prompt attention' },
              { id: 7, label: 'Professional waiter' }
            ]
          },
          {
            id: 8,
            label: 'Pleasant surroundings',
            icon: 'photo',
            children: [
              {
                id: 9,
                label: 'Happy atmosphere (not tickable)',
                tickable: false,
              },
              {
                id: 10,
                label: 'Good table presentation (disabled node)',
                disabled: true,
              },
              {
                id: 11,
                label: 'Pleasing decor',
              }
            ]
          },
          {
            id: 12,
            label: 'Extra information (has no tick)',
            noTick: true,
            icon: 'photo'
          },
          {
            id: 13,
            label: 'Forced tick strategy (to "strict" in this case)',
            tickStrategy: 'strict',
            icon: 'school',
            children: [
              {
                id: 14,
                label: 'Happy atmosphere',
              },
              {
                id: 15,
                label: 'Good table presentation',
              },
              {
                id: 16,
                label: 'Very pleasing decor',
              }
            ]
          }
        ]
      }
    ]

我的代码不能正常工作... 它只是一个没有递归的地图。

categories.map(e => {
        console.log(e.all_children)
        return {
          id: e.id,
          label: e.name,
          children: _.values(e).map(v => {
              return { id: v.id, label: e.name }
          })
        }
      })

我真的不知道如何做。如果你有任何关于如何做的想法,请帮助我。我一直在使用lodash搜索如何做,但是我找不到相关的代码。我对JavaScript不是很擅长。


2
你能否将输入数据以文本的形式发布,而不是图片,这样我们可以尝试处理它吗?请参阅为什么在SO上提问时不上传代码图像? - CertainPerformance
1个回答

6

您需要在回调函数内指定一个用于后续映射的函数。

const
    map = e => ({
        id: e.id,
        label: e.name,
        children: e.all_children.map(map) // recursive call
    }),
    tree = categories.map(map);

如果不使用all_children获取所有属性,您可以使用rest参数 ...来获取属性,并仅将子属性用于递归映射。

const
    map = ({ all_children = [], ...o }) => ({
        ...o,
        children: all_children.map(map) // recursive call
    }),
    tree = categories.map(map);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接