使用Lodash的递归地图

时间:2018-12-05 07:27:09

标签: javascript lodash

我有一个需要递归的数据,但是我不知道如何实现它。这是我的数据。 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不太好。

1 个答案:

答案 0 :(得分:3)

您需要指定一个函数,以便以后在回调内部进行映射。

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

要获取不带all_children的所有属性,可以将rest parameters ...作为属性,而仅将child属性用于递归映射。

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