Search code examples
javascriptjsonlodash

How to unflatten a JSON object and merge similar keys?


I have JSON in the given format :

{
"literature":
[
  {
   "category": "medical",
   "title": "med title",
   "abstract":"med abstract"
  },
  {
  "category": "medical",
  "title": "med title2",
  "abstract":"med abstract2"
  },
  {
  "category": "economics",
  "title": "eco title",
  "abstract":"eco abstract"
  },
  {
  "category": "science",
  "title": "sci title",
  "abstract":"sci abstract"
  }
]
  }

Desired Output :

{
"literature":
[
  {
"medical":
[
  {
   "title": "med title",
   "abstract":"med abstract"
  },
  {
  "title": "med title2",
  "abstract":"med abstract2"
  }
]
},
  {
  "economics":
[
  {
  "title": "eco title",
  "abstract":"eco abstract"
  }
 ]
},
  {
  "science":
   [
     {
  "title": "sci title",
  "abstract":"sci abstract"
     }
   ]
  }
]
}

I would convert the JSON to javascript object using JSON.parse() and then I would modify that object, making the category attribute as the key and merging the data inside the similar keys as illustrated above. I'm struck since the last three days, Please help me out.


Solution

  • Create new object and use for...of to rewrite values

    const response = {
    "literature":
    [
      {
       "category": "medical",
       "title": "med title",
       "abstract":"med abstract"
      },
      {
      "category": "medical",
      "title": "med title2",
      "abstract":"med abstract2"
      },
      {
      "category": "economics",
      "title": "eco title",
      "abstract":"eco abstract"
      },
      {
      "category": "science",
      "title": "sci title",
      "abstract":"sci abstract"
      }
    ]
      }
      
    function groupByCategory(items) {
     const grouped = {}
     for(const item of items) {
      grouped[item.category] = grouped[item.category] || [];
      const itemCopy = { ...item };
      delete itemCopy.category
      grouped[item.category].push(itemCopy)
     }
     
     console.log(grouped)
    }
    
    groupByCategory(response.literature)