【问题标题】:json - self referenced data into treejson - 自引用数据到树中
【发布时间】:2012-04-20 15:07:42
【问题描述】:

我有一个表格中的项目列表

ID - 父母 ID - 姓名

该列表采用如下 JSON 格式

[
    {
        "id": 1,
        "parent_id": 0,
        "name": "item 1"
    },
    {
        "id": 2,
        "parent_id": 0,
        "name": "item 2"
    },
    {
        "id": 3,
        "parent_id": 1,
        "name": "item 3"
    }
]

如何使用 javascript 将其转换为这样的嵌套列表? (嵌套层数没有限制)

[
    {
        "id": 1,
        "parent_id": 0,
        "name": "item 1",
        "children": [
            {
                "id": 3,
                "parent_id": 1,
                "name": "item 3"
            }
        ]
    },
    {
        "id": 2,
        "parent_id": 0,
        "name": "item 2"
    }
]

【问题讨论】:

    标签: javascript json tree hierarchy hierarchical-data


    【解决方案1】:

    这几乎是python中的一个衬里(假设每个父母只有一个孩子)

    import json
    from pprint import pprint
    
    Data = '[{"id": 1,"parent_id": 0,"name": "item 1"},
             {"id": 2,"parent_id": 0,"name": "item 2"},
             {"id": 3,"parent_id": 1,"name": "item 3"}]'
    List = json.loads(Data)
    [[IItem.update({'children' : List.pop(List.index(Item))})  for IItem in List if Item['parent_id'] == IItem['id']] for Item in List]
    Data = json.dumps(List)
    pprint(Data)
    

    如果您需要多个孩子,这会稍微改变一下。

    【讨论】:

    • 感谢和抱歉耽搁了!我正在寻找一个JS解决方案
    猜你喜欢
    • 2017-03-21
    • 2020-12-18
    • 1970-01-01
    • 2018-08-18
    • 2013-10-03
    • 1970-01-01
    • 2019-12-24
    • 2017-11-12
    • 2016-05-24
    相关资源
    最近更新 更多