【问题标题】:flatten js object to one list将 js 对象展平为一个列表
【发布时间】:2017-09-13 01:31:38
【问题描述】:

我很难找到一个好的解决方法来展平 JS-tree。如下所示,我有一棵树,其内容是一种“目录”。但是如何将其转换为扁平列表 JS-tree,并具有正确的父索引?

我想从“阶段 1”转换为“阶段 2”。

第一阶段:

[
    {
        "chapter": [
            {
                "head": [
                    {
                        "nr": [
                            "1"
                        ],
                        "label": [
                            "chapter 1"
                        ]
                    }
                ],
                "article": [
                    {
                        "head": [
                            {
                                "nr": [
                                    "1.1"
                                ],
                                "label": [
                                    "article 1.1"
                                ]
                            }
                        ],
                        "content": [
                            ""
                        ]
                    }
                ]
                // ...
            }
        ]
    }
]

第二阶段:

[
    {
        "id": 0,
        "name": "chapter",
        "parentId": null,
    },
    {
        "id": 1,
        "name": "head",
        "parentId": 0,
    },
    {
        "id": 2,
        "name": "nr",
        "parentId": 1,
    },
    {
        "id": 3,
        "name": "label",
        "parentId": 1,
    },
    {
        "id": 4,
        "name": "article",
        "parentId": 0,
    },
    {
        "id": 5,
        "name": "head",
        "parentId": 4,
    },
    {
        "id": 6,
        "name": "nr",
        "parentId": 5,
    },

    etc... etc..
]

【问题讨论】:

标签: javascript recursion javascript-objects


【解决方案1】:

如果有不清楚的地方请说出来。

function convert( input, result = [], parentId = null ){
  
  // Return if not an object (end of branch).
  if( typeof input !== "object" || input === null )
    return;
  
  // Convert children.
  if( Array.isArray(input) ){
    for( const element of input )
      convert(element, result, parentId);
    return result;
  }
  
  // Or add new property names and see what about their values.
  const keys = Object.keys(input);
  for( const key of keys ){
    const id = result.length;
    result.push({
      id: id,
      name: key,
      parentId: parentId
    });
    convert(input[key], result, id);
  }
  
}


const data = [{chapter:[{head:[{nr:["1"],label:["chapter 1"]}],article:[{head:[{nr:["1.1"],label:["article 1.1"]}],content:[""]}]}]}];

console.log(convert(data));

【讨论】:

  • 仅供参考,因为您在其他任何地方都使用const,您也可以考虑将循环声明const。一开始可能看起来很奇怪,但它确实很有用,并且强调了 let/const 的良好范围属性
猜你喜欢
  • 2019-02-10
  • 2017-12-04
  • 2017-06-13
  • 2017-05-22
  • 2022-07-21
  • 1970-01-01
  • 2011-03-14
  • 1970-01-01
  • 2015-02-03
相关资源
最近更新 更多