Nested Tree json 3 levels from flat json in javascript

  javascript, json, treeview

I have a flat JSON response from server. I need to convert it to nested JSON tree view.
I’m trying to build the nested tree view, like nested arrays. I could insert one level of tree view. But not sure how to form an array inside the tree view. Below things i tried and my sample. Please suggest.

const aTree = [{
    "materialId": 1,
    "materialType": 100,
    "itemCost": 30,
    "itemQuantity": 1,
    "itemQuantity1": 2,
    "itemQuantity2": 3
  },
  {
    "materialId": 1,
    "materialType": 100,
    "itemCost": 30,
    "itemQuantity": 2,
    "itemQuantity1": 2,
    "itemQuantity2": 3
  },
  {
    "materialId": 1,
    "materialType": 100,
    "itemCost": 50,
    "itemQuantity": 2,
    "itemQuantity1": 2,
    "itemQuantity2": 3
  },
  {
    "materialId": 1,
    "materialType": 200,
    "itemCost": 20,
    "itemQuantity": 2,
    "itemQuantity1": 2,
    "itemQuantity2": 3
  },
  {
    "aterialId": 1,
    "aterialType": 200,
    "temCost": 80,
    "temQuantity": 2,
    "temQuantity1": 2,
    "temQuantity2": 3
  },
  {
    "materialId": 2,
    "materialType": 300,
    "itemCost": 40,
    "itemQuantity": 0,
    "itemQuantity1": 2,
    "itemQuantity2": 3
  },
  {
    "materialId": 2,
    "materialType": 300,
    "itemCost": 40,
    "itemQuantity": 0,
    "itemQuantity1": 2,
    "itemQuantity2": 3
  },
  {
    "materialId": 2,
    "materialType": 200,
    "itemCost": 50,
    "itemQuantity": 0,
    "itemQuantity1": 2,
    "itemQuantity2": 3
  },
  {
    "materialId": 2,
    "materialType": 200,
    "itemCost": 50,
    "itemQuantity": 0,
    "itemQuantity1": 2,
    "itemQuantity2": 3
  },
]

var aTree1 = [];
aTree.forEach(function(a) {
  if (!this[a.materialId]) {
    this[a.materialId] = {
      Material: {
        MATID: [{
          materialId: a.materialId,
          MATType: [{
            materialType: a.materialType,
            ItemCO: [{
              itemCost: a.itemCost,
              Item: [{
                Qyan1: a.itemQuantity,
                Quan2: a.itemQuantity1,
                Quan3: a.itemQuantity2
              }]
            }]
          }]
        }],

      }
    };

    aTree1.push(this[a.materialId]);

  }
}, Object.create(null));

console.log(aTree1)

But i need the nested tree view,

Output should be like this

Source: Ask Javascript Questions

LEAVE A COMMENT