1

I'm given a JSON (tree structure JSON) and I'm creating an API that will insert all the data at once into the database (organizations with relations). the organisation may have multiple parents and children.

The JSON look's something like this:

{
  "org_name": "organisation",
  "childrens": [
    {
      "org_name": "company tree",
      "childrens": [
        {
          "org_name": "company one"
        },
        {
          "org_name": "company two"
        },
        {
          "org_name": "company three"
        }
      ]
    },
    {
      "org_name": "Big organisation",
      "childrens": [
        {
          "org_name": "company one"
        },
        {
          "org_name": "company two"
        },
        {
          "org_name": "company four"
        },
        {
          "org_name": "company three",
          "childrens": [
            {
              "org_name": "smal farm"
            }
          ]
        }
      ]
    }
  ]
}
 my database schema (which I'm thinking)
 id   |   org_name   |  level  | parent

 *level - tells at which level we are since this is a tree and helps to plot relations

How do I insert these records into the database with their relations? I need to do this in javascript.

code_freak
  • 45
  • 8

1 Answers1

0

const maintree = [{
  "org_name": "organisation",
  "childrens": [
    {
      "org_name": "company tree",
      "childrens": [
        {
          "org_name": "company one"
        },
        {
          "org_name": "company two"
        },
        {
          "org_name": "company three"
        }
      ]
    },
    {
      "org_name": "Big organisation",
      "childrens": [
        {
          "org_name": "company one"
        },
        {
          "org_name": "company two"
        },
        {
          "org_name": "company four"
        },
        {
          "org_name": "company three",
          "childrens": [
            {
              "org_name": "smal farm"
            }
          ]
        }
      ]
    }
  ]
}];


function recursiveBuild(tree, level, parent) {
  for(const item of tree) {
        if(item.org_name) {
        let html = document.getElementById(`test`).innerHTML;
            html += `orgname: ${item.org_name}, level: ${level}, parent: ${parent} <br/>`;
        document.getElementById(`test`).innerHTML = html;
        if(item.childrens) {
        recursiveBuild(item.childrens, level+1, item.org_name);
      } else return
    }
  }
}

recursiveBuild(maintree, 0, "");
<div id="test">
</div>

You can use a recursive function like this to insert your records depending on your database. Here I have explained using HTML and added string after each line break for your code to build a flat structure like table.

deep206
  • 106
  • 2
  • 10