将js对象展平为一个列表

时间:2017-04-17 12:17:54

标签: javascript recursion javascript-objects

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

我想转换为第1阶段'到第2阶段'

阶段1:

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

阶段2:

[
    {
        "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..
]

1 个答案:

答案 0 :(得分: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));