笛卡尔实现的树递归

我需要帮助才能从树上找到所有可能的组合

我阅读了很多有关笛卡尔积的文档,尝试了很多东西,但似乎都无法正常工作...

这是我的树

var data = [
  {
    "id": 5,"name": "Support papier","type": "filter","children": [
      {
        "id": 24,"name": "60 g/m² papier mat","type": "value","children": []
      },{
        "id": 7,"name": "90 g/m² papier couché","children": [
          {
            "id": 8,"name": "Propriété papier","children": [
              {
                "id": 18,"name": "Papier mat","children": [],},{
                "id": 60,"name": "Papier brillant",}
            ]
          }
        ],}
    ]
  }
]

这是我的预期结果:

[
  [
    {id: 5,name:"support papier",type: "filter"},{id: 24,name:"60 g/m² papier mat",type: "value"},],[
    {id: 5,{id: 7,name:"90 g/m² papier mat",{id: 8,name:"Propriété papier",{id: 18,name:"Papier mat",{id: 60,name:"Papier brillant",]
]

当然,每个空数组都可以填充...:)

感谢您的帮助:)

h11111_h 回答:笛卡尔实现的树递归

您可以获取每个级别并将下一个较低级别映射到结果集。

  

现在,它在做什么?

     

收集数据的第一步是将所有节点都放在子对象的末尾。

     

另一部分是对具有对象的孩子使用笛卡尔乘积

type === 'value'
     

这可以分为两个步骤

     
      
  1. 通过获取数据来收集所有项目,并将这些项目与实际对象进行映射。

  2.   
  3. 从一系列项目中创建一个cartesian product

  4.   
     

其余的只是用parts推送一个新数组并添加实际对象(没有子对象),或者如果没有子对象可用,则仅是数组中的实际对象。

function getData(array) {
    return array.reduce((r,{ children,...o }) => {
        if (children.length) {
            var parts = o.type === 'value'
                    ? children
                        .map(({ children = [],...p }) => getData(children).map(q => [p,...q]))
                        .reduce((a,b) => a.reduce((r,v) => r.concat(b.map(w => [].concat(v,w))),[]))
                    : getData(children);

            r.push(...parts.map(q => [o,...q]));
        } else {
            r.push([o]);
        }
        return r;
    },[]);
}

var data = [{ id: 5,name: "Support papier",type: "filter",children: [{ id: 24,name: "60 g/m² papier mat",type: "value",children: [{ id: 9,name: "Finition",children: [{ id: 19,name: "Sans finition",children: [] },{ id: 20,name: "Vernis anti UV",children: [] }] },{ id: 8,name: "Propriété papier",children: [{ id: 60,name: "Papier brillant",{ id: 18,name: "Papier mat",children: [] }] }] },{ id: 7,name: "90 g/m² papier couché",children: [{ id: 8,children: [{ id: 18,{ id: 60,children: [] }] }] }] }],result = getData(data);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

本文链接:https://www.f2er.com/3160573.html

大家都在问