Group JSON elements based on their values

Good day,

I am currently working on creating a JSON file that organizes Portuguese parishes by district, municipality, and parish. The structure I am aiming for is as follows:

{
  "district": "Aveiro",
  "OfficialCodeDistrict": "01",
  "municipalities": [
    {
      "municipality": "Arouca",
      "OfficialCodeMunicipality": "0104",
      "parishes": [
        {
          "parish": "Fermedo",
          "OfficialCodeParish"
        },
        {
          "parish": "Várzea",
          "OfficialCodeParish": "010420"
        },
        {
          "parish": "Escariz",
          "OfficialCodeParish": "010409"
        },
        {
          "parish": "Mansores",
          "OfficialCodeParish": "010413"
        }
      ]
    },
    {
      "municipality": "Águeda",
      "OfficialCodeMunicipality": "0101",
      "parishes": [
        {
          "parish": "Fermentelos",
          "OfficialCodeParish": "010109"
        },
        {
          "parish": "Préstimo e Macieira de Alcoba",
          "OfficialCodeParish": "010127"
        }
      ]
    }
  ]
}

Each district contains municipalities, and within each municipality, we list all the parishes. I utilized an existing JSON file obtained from an Excel export, which can be found here

Referring to a question on StackOverflow, I managed to group the municipalities within each district. However, I am currently struggling with grouping municipalities within their respective district, as illustrated in the linked image:

JSON Output

I attempted to manipulate the JSON structure by iterating through the municipalities within each district, but I am facing challenges in merging this information back into the original object. Any assistance on achieving the desired JSON structure would be greatly appreciated!

Output Per District

Thank you for your help in advance!

Answer №1

Here is a way to achieve the desired result:

First, create an object with districts as keys. Then, for each district, create an object for the corresponding municipality with the municipality name as the key.

After parsing the data, you can remove the indices using the Object.values method.

const transform  = data => Object.values(data.reduce((res, item) => {
  const district = item['Official Name District']
  const municipality = item['Official Name Municipality']
  const existingDistrict = res[district] || {district, OfficialCodeDistrict: item['Official Code District'], municipalities: {} }
  const existingMunicipality = existingDistrict.municipalities[municipality] || {municipality, OfficialCodeMunicipality: item['Official Code Municipality'], parishes:[]}
  
  return {
   ...res,
   [district]: {
     ...existingDistrict,
     municipalities: {    
       ...existingDistrict.municipalities,
       [municipality]: {
       ...existingMunicipality,
       parishes: [...existingMunicipality.parishes, {parish: item['Official Name Parish'], OfficialCodeParish: item['Official Code Parish']}]
       }
     }
   }
  }
  
}, {})).map(d => ({...d, municipalities: Object.values(d.municipalities)}))


const data = [
{
"Official Code District": "01",
"Official Name District": "Aveiro",
"Official Code Municipality": "0104",
"Official Name Municipality": "Arouca",
"Official Code Parish": "010411",
"Official Name Parish": "Fermedo",
"Type": "parish"
},
{
"Official Code District": "01",
"Official Name District": "Aveiro",
"Official Code Municipality": "0109",
"Official Name Municipality": "Santa Maria da Feira",
"Official Code Parish": "010913",
"Official Name Parish": "Lourosa",
"Type": "parish"
},
{
"Official Code District": "01",
"Official Name District": "Aveiro",
"Official Code Municipality": "0109",
"Official Name Municipality": "Santa Maria da Feira",
"Official Code Parish": "010914",
"Official Name Parish": "Milheirós de Poiares",
"Type": "parish"
},
{
"Official Code District": "01",
"Official Name District": "Aveiro",
"Official Code Municipality": "0111",
"Official Name Municipality": "Mealhada",
"Official Code Parish": "011107",
"Official Name Parish": "Vacariça",
"Type": "parish"
},
{
"Official Code District": "01",
"Official Name District": "Aveiro",
"Official Code Municipality": "0118",
"Official Name Municipality": "Vagos",
"Official Code Parish": "011801",
"Official Name Parish": "Calvão",
"Type": "parish"
},
{
"Official Code District": "01",
"Official Name District": "Aveiro",
"Official Code Municipality": "0119",
"Official Name Municipality": "Vale de Cambra",
"Official Code Parish": "011906",
"Official Name Parish": "Macieira de Cambra",
"Type": "parish"
},
{
"Official Code District": "01",
"Official Name District": "Aveiro",
"Official Code Municipality": "0119",
"Official Name Municipality": "Vale de Cambra",
"Official Code Parish": "011907",
"Official Name Parish": "Roge",
"Type": "parish"
},
{
"Official Code District": "02",
"Official Name District": "Beja",
"Official Code Municipality": "0204",
"Official Name Municipality": "Barrancos",
"Official Code Parish": "020401",
"Official Name Parish": "Barrancos",
"Type": "parish"
},
{
"Official Code District": "02",
"Official Name District": "Beja",
"Official Code Municipality": "0206",
"Official Name Municipality": "Castro Verde",
"Official Code Parish": "020605",
"Official Name Parish": "São Marcos da Ataboeira",
"Type": "parish"
}]

console.log(transform(data))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Kik Card - Using Synchronous XMLHttpRequest within the Kik.js Script

Getting ready to create a mobile web app powered by Kik! First step, insert the Kik.js script at the bottom of your HTML page... <!-- add this script to your webpage --> <script src="http://cdn.kik.com/kik/2.3.6/kik.js"></script> Excel ...

Trouble with installing Enmap due to better-sqlite3 error

For a while now, I've been struggling to get enmap installed. Despite searching the web exhaustively, I haven't come across any solutions that work for me. Every time I try npm i enmap, I consistently encounter this frustrating error: One part o ...

Don't initiate the next fetch until the previous one has completed

I am currently working on sending a list of data to Google Cloud. The code I have been using is as follows: const teams = ['LFC', 'MUFC', 'CFC']; teams.forEach(team => { fetch({ url: URL, method: 'PUT ...

Unable to convert information into JSON format

In my PHP file, I created a JSON array like this: $array[1] = "string1"; $array[2] = "string2"; $array[3] = "string3"; echo json_encode($array); I want to assign each string to different ID tags in my HTML, but the following code didn't w ...

Can you tell me the specific parameter used in the beforeSend function in jQuery?

I have been examining some instances of the beforeSend callback function. Sometimes, these examples include an input parameter: beforeSend:function(req) or beforeSend:function(xhr). I assume that this parameter represents the XMLHTTPRequest of the jquery ...

Accessing new information seamlessly without the need for page refresh

For optimal mobile viewing of my website, I am considering implementing a select element. Here are the available options: HTML: <select name="select-choice-8" id="select-choice-nc"> <optgroup label="News"> & ...

Issue with retrieving attributes in the directive

One of the challenges I encountered is incorporating a directive that wraps the jQuery FullCalendar plugin into my project. Here is how I implement the directive: <div sg-calendar format-column-header-month='dddd' format-co ...

Create a feature in three.js that allows users to click on an object to display information about the

After loading an object using the GLTF loader into my scene, I want to create a point on this object to display popup info. Is there a way to add a point to a specific location on the object? ...

Optimizing the management of optional post fields in an Express.js application

When creating an endpoint with Express that includes both mandatory and non-mandatory fields in the post request, what is the optimal strategy for handling this? Would it be best to use something like if (field exists in req.body) { set variable } else { ...

Error Occurred While Setting Geolocation in Leaflet Webview Using Javascript/HTML SetView Function

I am attempting to showcase a remote HTML webpage in my Android Studio WebView. The webpage displays 2D geographic points data of a location zoomed in over the user's location, like this: var map = L.map('map', { layers: [osmMap], ...

Using the moment library in Angular to convert date and time can sometimes lead to errors

Whenever I attempt to convert a Gregorian date to a Persian date, the minute value in the conversion ends up becoming an error. For instance, let's say I want to convert this specific date and time to a Persian date: 2020-09-14T16:51:00+04:30 should ...

Tips for generating various series using dx-Chartjs

Trying to visualize ratings based on their type is proving to be difficult as I can't seem to figure out how to group the series according to types. The available chart options are: $scope.chartOptions = { dataSource: data, c ...

Guide to setting up 2-factor authentication on GitHub using an AJAX request

My task is to query GitHub for all open pulls, but I'm new to this and don't have anyone to turn to for guidance. The only resources I've found so far are the documentation on . I came across a solution on that explains how to provide a us ...

Excessive requests to location or history APIs in a brief period of time

Alert: Reached maximum update depth. This issue may arise when a component invokes setState within useEffect without a dependency array, or if any of the dependencies change on each render. const OwnerPage = () => { const onOpen = useAgencyModal((s ...

Tips on dividing and recycling mongodb connection in Node.js

I am currently troubleshooting the connection to MongoDB using Node.js. The code I have in a file named mongodb.js is as follows: const mongoClient = require('mongodb').MongoClient; const env = process.env.NODE_ENV || 'development'; co ...

An effective approach to positioning HTML elements at specific X and Y coordinates

I have an innovative project idea! The concept is to enable users to create points by clicking on the display. They can then connect these points by clicking again. However, I am facing a challenge when it comes to creating HTML elements at the exact loc ...

Oops! There seems to be a problem with the Node.js App. The MongooseError is indicating that the parameter `uri` in the `openUri()` function should be a string,

I've encountered an issue with my Next.js app involving MongoDB that I've been struggling to resolve. Hoping someone here can provide some insight and help me out. This is quite crucial for my project. First, I'll share the code from my serv ...

Interact with Node.js server to fetch JSON data from Python and display it on an HTML client using Ajax

Seeking a way to retrieve JSON data in my HTML page using Ajax, I have a Node.js server set up for handling requests. The JSON data is generated by Python code on the server. Is it worth saving the JSON in a database for access? Seems overly complicated ...

Utilize a stored string as the destination for the content of an object

We are currently working on processing a large amount of json data and trying to specify which parts of it to use using string variables. My goal is to convert a string into an object path to access the content of an item. The following code works correc ...

Guidance on creating a custom color selection tool for a specific task

Looking for assistance in converting a code snippet that uses <button> elements to select colors into a color picker. I am unsure how to retrieve the selected color and use it within a JavaScript function. Can someone provide guidance on this? Here i ...