Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

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

I have a json file with the following structure:

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

I would like it to have the following structure:

  {
    "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"
                  }
                ]
              }
            ]
          }
        ]
      }
    ]
  }

I would like to have a parent-children hierarchy relationship so that it would be easier to draw a collapsible-tree diagram with nodes.Please forgive if the indentation is not proper.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could use a recursive approach by using the object and a parent value.

For getting the wanted style with Root element, you need to hand over a new object which follows the same building rule than the inner objects of the given data.

{
    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; }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...