簡體   English   中英

將常規json文件轉換為d3 flare.json使用的父子分層json

[英]Converting a regular json file to a parent-child hierarchical json as used by d3 flare.json

我有一個具有以下結構的json文件:

  {
    "a": "b",
    "c": "d",
    "e": {
      "f": "g",
      "h": "i"
    }
  }

我希望它具有以下結構:

  {
    "name": "Root",
    "parent": "null",
    "children": [
      {
        "name": "a",
        "parent": "Root",
        "children": [
          {
            "name": "b",
            "parent": "a"
          }
        ]
      },
      {
        "name": "c",
        "parent": "Root",
        "children": [
          {
            "name": "d",
            "parent": "d"
          }
        ]
      },
      {
        "name": "e",
        "parent": "Root",
        "children": [
          {
            "name": "f",
            "parent": "e",
            "children": [
              {
                "name": "g",
                "parent": "f"
              },
              {
                "name": "h",
                "parent": "e",
                "children": [
                  {
                    "name": "i",
                    "parent": "h"
                  }
                ]
              }
            ]
          }
        ]
      }
    ]
  }

我希望有一個父子層次關系,以便更容易繪制帶有節點的可折疊樹圖。如果縮進不合適,請原諒。

您可以通過使用對象和父值來使用遞歸方法。

為了獲得帶有Root元素的所需樣式,您需要移交一個新對象,該對象遵循與給定數據的內部對象相同的構建規則。

 { Root: data[0] } 

 const getObjects = (o, parent) => o && typeof o === 'object' ? Object.entries(o).map(([name, v]) => ({ name, parent, children: getObjects(v, name) })) : [{ name: o, parent }]; var data = [{ a: "b", c: "d", e: { f: "g", h: "i" } }], result = getObjects({ Root: data[0] }, 'null'); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

這是一種可能性:

 const treeify = (orig) => Object.entries(orig).map( ([k, v]) => (Object.assign({name: k}, typeof v == 'object' ? {children: treeify(v)} : {children: {name: v}} )) ) const convert = (orig) => ({name: 'Root', children: treeify(orig)}) const orig = {"a": "b", "c": "d", "e": {"f": "g", "h": "i"}} console.log(convert(orig)) 

treeify處理繁重的工作, convert是添加Root節點的簡單包裝器。 請注意,沒有嘗試創建parent節點,因為根據注釋, parent節點是不必要的。

更新資料

Nina Scholz確實提供了父母(我認為這會困難得多!)的答案很明確,這表明該版本的替代方案也包含了該版本。 即使沒有父母,我也更喜歡這個版本的convert

 const treeify = (orig, parent) => Object.entries(orig).map( ([k, v]) => (Object.assign({name: k, parent}, typeof v == 'object' ? {children: treeify(v, k)} : {children: {name: v, parent: k}} )) ) const convert = (orig) => treeify({Root: orig}, 'null')[0] const orig = {"a": "b", "c": "d", "e": {"f": "g", "h": "i"}} console.log(convert(orig)) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM