Convert JSON array of objects into nasted json tree usning JavaScript

Junaid Shabbir

I have a API which return JSON array of objects. Which need to be converted into nested JSON array in a parent/child relation based on "parientid" in each node. Where "parientid" is null it will be root nodes and other will be child node of there parent node. Below is the sample JSON array which I get from API.

  var API_DATA = [
  {
    "DIAGID": 1,
    "DIAGNOSIS": "Certain infectious or parasitic diseases ",
    "DIAGTYPE": "Chapter",
    "PARENTID": null,
  },
  {
    "DIAGID": 2,
    "DIAGNOSIS": "Gastroenteritis or colitis of infectious origin  ",
    "DIAGTYPE": "Section",
    "PARENTID": 1,
  },
  {
    "DIAGID": 3,
    "DIAGNOSIS": "Bacterial intestinal infections",
    "DIAGTYPE": "Category",
    "PARENTID": 2,
  },
  {
    "DIAGID": 4,
    "DIAGNOSIS": "Cholera",
    "DIAGTYPE": "Group",
    "PARENTID": 3,
  },
  {
    "DIAGID": 5,
    "DIAGNOSIS": "Intestinal infection due to other Vibrio",
    "DIAGTYPE": "Disease",
    "PARENTID": 4,
  },
  {
    "DIAGID": 6,
    "DIAGNOSIS": "Intestinal infections due to Shigella",
    "DIAGTYPE": "Disease",
    "PARENTID": 4,
  },
  {
    "DIAGID": 7,
    "DIAGNOSIS": "Intestinal infections due to Escherichia coli",
    "DIAGTYPE": "Disease",
    "PARENTID": 4,
  },
  {
    "DIAGID": 8,
    "DIAGNOSIS": "Neoplasms",
    "DIAGTYPE": "Chapter",
    "PARENTID": null,
  },
  {
    "DIAGID": 9,
    "DIAGNOSIS": "Neoplasms of brain or central nervous system",
    "DIAGTYPE": "Section",
    "PARENTID": 8,
  },
  {
    "DIAGID": 10,
    "DIAGNOSIS": "Primary neoplasms of brain ",
    "DIAGTYPE": "Category",
    "PARENTID": 9,
  },
  {
    "DIAGID": 11,
    "DIAGNOSIS": "Gliomas of brain",
    "DIAGTYPE": "Group",
    "PARENTID": 10,
  },
  {
    "DIAGID": 12,
    "DIAGNOSIS": "Glioblastoma of brain",
    "DIAGTYPE": "Disease",
    "PARENTID": 11,
  },
  {
    "DIAGID": 13,
    "DIAGNOSIS": "Other specified gliomas of brain",
    "DIAGTYPE": "Disease",
    "PARENTID": 11,
  }
]

I want to convert it into tree format in parent/child relation based on "ParentId" in each object. Below is the example of JSON in which I want to convert it. I want "DIAGID" as value and "DIAGNOSIS" as name.

const data = {
  label: 'search me',
  value: 'searchme',
  children: [
    {
      label: 'search me too',
      value: 'searchmetoo',
      children: [
        {
          label: 'No one can get me',
          value: 'anonymous',
        },
      ],
    },
  ],
}

I am new to javascript I have used javascript array, map function but need little guide on what approach should i follow.

Nina Scholz

You could take a standard approach for trees with a single loop.

var data = [{ DIAGID: 1, DIAGNOSIS: "Certain infectious or parasitic diseases ", DIAGTYPE: "Chapter", PARENTID: null }, { DIAGID: 2, DIAGNOSIS: "Gastroenteritis or colitis of infectious origin  ", DIAGTYPE: "Section", PARENTID: 1 }, { DIAGID: 3, DIAGNOSIS: "Bacterial intestinal infections", DIAGTYPE: "Category", PARENTID: 2 }, { DIAGID: 4, DIAGNOSIS: "Cholera", DIAGTYPE: "Group", PARENTID: 3 }, { DIAGID: 5, DIAGNOSIS: "Intestinal infection due to other Vibrio", DIAGTYPE: "Disease", PARENTID: 4 }, { DIAGID: 6, DIAGNOSIS: "Intestinal infections due to Shigella", DIAGTYPE: "Disease", PARENTID: 4 }, { DIAGID: 7, DIAGNOSIS: "Intestinal infections due to Escherichia coli", DIAGTYPE: "Disease", PARENTID: 4 }, { DIAGID: 8, DIAGNOSIS: "Neoplasms", DIAGTYPE: "Chapter", PARENTID: null }, { DIAGID: 9, DIAGNOSIS: "Neoplasms of brain or central nervous system", DIAGTYPE: "Section", PARENTID: 8 }, { DIAGID: 10, DIAGNOSIS: "Primary neoplasms of brain ", DIAGTYPE: "Category", PARENTID: 9 }, { DIAGID: 11, DIAGNOSIS: "Gliomas of brain", DIAGTYPE: "Group", PARENTID: 10 }, { DIAGID: 12, DIAGNOSIS: "Glioblastoma of brain", DIAGTYPE: "Disease", PARENTID: 11 }, { DIAGID: 13, DIAGNOSIS: "Other specified gliomas of brain", DIAGTYPE: "Disease", PARENTID: 11 }],
    tree = function (data, root) {
        var t = {};
        data.forEach(({ DIAGID, DIAGNOSIS, PARENTID }) => {
            Object.assign(t[DIAGID] = t[DIAGID] || {}, { label: DIAGID, name: DIAGNOSIS });
            t[PARENTID] = t[PARENTID] || {};
            t[PARENTID].children = t[PARENTID].children || [];
            t[PARENTID].children.push(t[DIAGID]);
        });
        return t[root].children;
    }(data, null);

console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Make json from array of objects javascript

분류에서Dev

JavaScript: Add JSON objects from one array to another array conditionally

분류에서Dev

nasted json 객체에 액세스

분류에서Dev

Convert JSON Data to JavaScript 2D Array

분류에서Dev

Convert output of tree command to json format

분류에서Dev

jOOQ JSON formatting as array of objects

분류에서Dev

Jackson: Convert JSON to object: ArrayList of objects with arraylist of objects with arraylist of objects

분류에서Dev

Convert JSON bidimensional array to an AS3 array

분류에서Dev

Unable to json_encode array of objects

분류에서Dev

JSON object expecting an array of objects but gets nothing

분류에서Dev

Reduce JSON object containing JSON objects into an array of the form [Path, Value]

분류에서Dev

Access JSON Array through Javascript

분류에서Dev

Convert JSON Array to Object Node js

분류에서Dev

How to get json value from json array using javascript

분류에서Dev

Filter Array Before Push JSON Object to Javascript

분류에서Dev

coffeescript/javascript access JSON array @initialize and @refresh

분류에서Dev

Move values from JSON to javascript array

분류에서Dev

PointlnPolygon function not processing multiple objects from JSON Array

분류에서Dev

Unexpected results, Parse Array of JSON Objects in ASP.Net

분류에서Dev

How to convert a json string into an individual character array in bash?

분류에서Dev

Javascript array of objects undefined

분류에서Dev

Erlang, Nested JSON objects

분류에서Dev

List of Objects To Json String

분류에서Dev

Merge and compare with in JSON objects

분류에서Dev

Finding JSON objects in mongoDB

분류에서Dev

Parsing JSON objects to post

분류에서Dev

Populating JSON objects in DataTables

분류에서Dev

Companion objects, implicits, and Json

분류에서Dev

Convert array to string Javascript

Related 관련 기사

뜨겁다태그

보관