javascript - 递归映射函数

标签 javascript recursion

我很难弄清楚如何执行这个递归映射函数。
我有一个看起来像这样的数组。

var array = [
      {
        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',
              }
            ]
          }
        ]
      }
    ];

这是数组的样子......
enter image description here

如您所见, children 是recursive .

我需要将它们放入一个数组中。
我的代码不起作用并且有错误。
const result = [];   
const map = (e) => {

    result.push({
        id: e.id,
        label: e.label,
    })

    e.children.map(map)


};

array.map(map);

错误出现在 e.children.map(map) .
enter image description here

我需要将它们全部推送到数组变量中,但我不知道该怎么做。泰

最佳答案

您需要检查当前项目是否有 children元素,您可以使用 forEach而是因为 map返回新数组和 forEach只是去扔每个元素。

const cb = (e) => {
    res.push({
        id: e.id,
        label: e.label,
    });
    e.children && e.children.forEach(cb);
}
array.forEach(cb);

关于javascript - 递归映射函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54245284/

相关文章:

c - C 中的递归链表反转函数

python - 在python中将递归函数转换为尾递归函数

haskell - 为什么替代的一些和许多是haskell中的无限递归函数

javascript - 在 Javascript 中将 HTML 文件内容转换为字符串

javascript - 无法读取未定义错误的属性推送

javascript - 使用更少的缓存破坏静态图像

javascript - (函数 fn(){ ... })() 不起作用

c++ - 何时使用递归互斥锁?

Javascript - 检查 cookie 是否已设置

performance - (Lisp) 我可以让它更有效率吗?