Search code examples
javascriptarrayslodash

Convert Array to nested Object Array


I have a question, how to Convert Array to nested Object Array? I.e. I have a following array:

const myArray = [
    { "depart_id": 1, "depart_name": "computer science", "faculty_name": "faculty of natural science", "faculty_id": 1 },
    { "depart_id": 2, "depart_name": "computer programming", "faculty_name": "faculty of natural science", "faculty_id": 1 },
    { "depart_id": 3, "depart_name": "chemical engineering", "faculty_name": "faculty of engieering", "faculty_id": 2 },
    { "depart_id": 4, "depart_name": "marketing", "faculty_name": "faculty of business", "faculty_id": 3 },
]

And please explain me how I can convert this arrays to the following format:

const resultArray = [
    {
        "faculty_id": 1,
        "faculty_name": "faculty of natural science",
        "department": [
            {
                "depart_id": 1,
                "depart_name": "computer science"
            },
            {
                "depart_id": 2,
                "depart_name": "computer programming"
            }
        ]
    },
    {
        "faculty_id": 2,
        "faculty_name": "faculty of engieering",
        "department": [
            {
                "depart_id": 3,
                "depart_name": "chemical engineering"
            }
        ]
    },
    {
        "faculty_id": 3,
        "faculty_name": "faculty of business",
        "department": [
            {
                "depart_id": 4,
                "depart_name": "marketing"
            }
        ]
    }
]

Solution

  • const myArray = [{
        "depart_id": 1,
        "depart_name": "computer science",
        "faculty_name": "faculty of natural science",
        "faculty_id": 1
      },
      {
        "depart_id": 2,
        "depart_name": "computer programming",
        "faculty_name": "faculty of natural science",
        "faculty_id": 1
      },
      {
        "depart_id": 3,
        "depart_name": "chemical engineering",
        "faculty_name": "faculty of engieering",
        "faculty_id": 2
      },
      {
        "depart_id": 4,
        "depart_name": "marketing",
        "faculty_name": "faculty of business",
        "faculty_id": 3
      },
    ];
    
    const result = [];
    
    myArray.forEach(function(arr) {
      const dept = result.find(res => res.faculty_id === arr.faculty_id);
    
      const {
        faculty_id,
        faculty_name,
        depart_id,
        depart_name
      } = arr;
    
      if (!dept) {
        result.push({
          faculty_id,
          faculty_name,
          department: [{
            depart_id,
            depart_name
          }]
        })
      } else {
        dept.department.push({
          depart_id,
          depart_name
        })
      }
    })
    
    console.log(result);