Convert a JSON array into a new format

Here is the JSON data input provided:

"rows": [
          [
             1,
             "GESTORE_PRATICHE",
             1,
             "GESTORE PRATICHE",
             "canViewFolderManagement"
          ],
          [
             2,
             "ADM",
             1,
             "AMMINISTRATORE",
             "canViewFolderManagement"
          ],
          [
             2,
             "ADM",
             2,
             "AMMINISTRATORE",
             "canViewOther"
          ]  
     ]

The task at hand is to transform this data into a new JSON format using underscorejs as shown below:

   [
     {
            "groupID": "1",
            "groupName":"GESTORE_PRATICHE",
            "groupDescr":"GESTORE PRATICHE",
            "functionList": [
                 {
                      "1": "canviewfoldermanagement"
                 }
             ]
        },
        {
            "groupID": "2",
            "groupName":"ADM",
            "groupDescr":"AMMINISTRATORE",
            "functionList": [
                 {
                      "1": "canviewfoldermanagement",
                      "2": "canviewOther"
                 }
             ]
        }
    ]

To achieve this, an object array with single elements grouped by ID (the first key of each one) is needed. Attempts have been made using underscore js filter and groupby functions but with limited success...

One such attempt was made in angular 2 as seen below:

constructor(private sanitizer: DomSanitizer, private http: Http) {
        this.source = new LocalDataSource(this.data); // create the source ;
        this.http.get('app/json/profileInput.json')
                .subscribe(res => this.data = res.json());

        let profileInput; 
        this.http.get('app/json/profileInput.json')
        .subscribe(res =>{
            profileInput = res.json()
            //console.log(JSON.stringify(profileInput));
            this.profileConstructor(profileInput.rows);
            }
        );


    }

    profileConstructor(profileRows){
       console.log(JSON.stringify(
                _.object(JSON.stringify([_.object([profileRows], ['riga'])], [1, 2, 3, 4, 5]))
            )
       );
    } ;

Answer №1

If there is no existing group, you have the option to utilize a Map and create a new entry.

function categorize(array) {
    var map = new Map;

    array.forEach(function (o) {
        var group = map.get(o[0]) || { groupID: o[1], groupName: o[1], groupDescr: o[3], functionList: {} };
        if (!map.has(o[0])) {
            map.set(o[0], group);
        }
        group.functionList[o[2]] = o[4];
    });
    return [...map.values()];
}

var items = [[1, "GESTORE_PRATICHE", 1, "GESTORE PRATICHE", "canViewFolderManagement"], [2, "ADM", 1, "AMMINISTRATORE", "canViewFolderManagement"], [2, "ADM", 2, "AMMINISTRATORE", "canViewOther"]],
    result = categorize(items);

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

Answer №2

With the power of the array reduce() method, transforming an existing array into an object with customized values is a breeze.

reduce requires two parameters:

  • First parameter: a new variable (could be an object, array, or any other data type) to be returned

  • Second parameter: the elements of the array

arr = [
  [
    1,
    "GESTORE_PRATICHE",
    1,
    "GESTORE PRATICHE",
    "canViewFolderManagement"
  ],
  [
    2,
    "ADM",
    1,
    "AMMINISTRATORE",
    "canViewFolderManagement"
  ],
  [
    2,
    "ADM",
    2,
    "AMMINISTRATORE",
    "canViewOther"
  ]
]

arr = arr.reduce((a, b) => {
  let flag = false,
    obj = {};
  a.forEach(item => {
    if (item.groupID === b[0] && item.groupName === b[1] && item.groupDescr === b[3]) {
      item.functionList[0][b[2]] = b[4];
      flag = true;
    }
  });
  if (!flag) {
    obj[b[2]] = b[4];
    a.push({
      "groupID": b[0],
      "groupName": b[1],
      "groupDescr": b[3],
      "functionList": [obj]
    });
  }
  return a;
}, []);

console.log(arr);

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

What is the best way to pass an input value into a function when a form is submitted in Angular 6?

When I press enter, my code works perfectly and the performSearch function runs successfully. However, when I attempt to run the function by clicking the submit button, I encounter the following error: Error: cannot read property of undefined This is m ...

Storing extensive volumes of searchable JSON data

I'm in search of a database solution that can meet the following requirements: Store flat, random JSON structures separated by table names (e.g. random_json_table_1, random_json_table_2). Handle a high volume of insert operations (over 10,000 per se ...

The reset function for the selector is failing to properly reset the data within the table

I need help with a selector that has multiple options and a reset button. When the reset button is clicked, it should reset the selector back to the first option. Although the selector resets as expected when the button is clicked, the data in the table r ...

Can the ajaxsetup error handler be used with the POST method?

I have a strange question - does the global error handler applied when using ajaxsetup get triggered in case of an Ajax error on a POST request? I've tried handling Ajax errors in several places, but the error handler is only being hit for GET reques ...

How can you troubleshoot code in NextJS API routes similar to using console.log?

Incorporating nextjs API routes into my upcoming project has been a priority, and I recently encountered an issue with code execution upon sending a POST request. Debugging has proven to be challenging since I am unable to use conventional methods like co ...

What are the steps to enable a Vue component to handle its own transitions?

I am looking for a way to handle enter and leave animations in Vue when components are mounted or removed. My goal is to consolidate all the animation code into its own component for better organization. <template> <transition @enter="enter" ...

Transmit information from a Chrome extension to a Node.js server

Recently, I developed a basic Chrome extension that captures a few clicks on a specific webpage and stores the data in my content_script. Now, I am looking for ways to transmit this data (in JSON format) to my node.js file located at /start. I am seeking ...

Error: Unrecognized HTML, CSS, or JavaScript code detected in template

I'm currently utilizing the "Custom HTML Tag" option in GTM with my code below, but encountering an error when attempting to publish: Invalid HTML, CSS, or JavaScript found in template. It seems that GTM may not support or recognize certain tag attri ...

The React Callservice script is failing to fetch the required data from the Node.js script responsible for making the API call

Recently, I decided to create a basic webpage using React.js to display data fetched from an API. Although the project is intended to be straightforward, my lack of recent development experience has led to a perplexing issue that I can't seem to resol ...

Populate a row in a dataframe with JSON objects based on values in another column

I have a dataset with the following attributes: ID A1 B1 C1 A2 B2 C2 A3 B3 C3 AA 1 3 6 4 0 6 BB 5 5 4 6 7 9 CC 5 5 5 I am looking to add a new column called Z that will group each row into a JSON list of records, and then rename ...

Golang decodes JSON using static typing rather than dynamic typing

I used to believe that json.Marshal utilized reflection to examine the passed type and then decoded it accordingly. However, I encountered an issue when I had a variable with a static type of any which actually stored a struct, and when passed to json.Unma ...

Attempting to fetch a JSON object from PHP to Android

I'm currently working on parsing an array from my PHP script to my Android app. Below is a snippet of my Android code: public void func4(View view) throws Exception { final String TAG_CONTACTS = "response"; AsyncHttpClient client = new AsyncH ...

Utilize JavaScript to trigger a function depending on the selected options from dropdown menus

I've been working on a fun little project for a web page where users can select two items from a drop-down menu and then click a button to play a sound corresponding to their selections. However, I'm facing some challenges with getting my JavaScr ...

Developing a user-friendly widget for a website that is not optimized for mobile devices

Here's the backstory: I'm currently in the process of creating a mobile-friendly widget for my clients. Unfortunately, they have web pages that are not optimized for mobile devices, and it doesn't seem like that will change anytime soon. Th ...

Restrict page scrolling to the vertical position of a specified div [Using jQuery, javascript, and HTML]

Currently, I am in the process of developing a personal website that features numerous expandable items. My goal is to restrict the page scrolling to the height of the expanded item once it is opened. I do not want users to be able to scroll above or below ...

WCF JSON Post functions correctly in Visual Studio but encounters issues in IIS 7.5

I'm experiencing a strange issue with my WCF Service in IIS. GET requests are functioning properly, but when it comes to POST requests, they only work when I run the service from Visual Studio. When I try to use IIS, I receive an Error 400 Bad Request ...

Whenever my code is used within Google Sites, it triggers the opening of a new and empty tab

When using this code inside an HTML box in Google Sites, a problem arises. It seems to work perfectly fine in Internet Explorer and Chrome when saved to an HTML file. However, within Google Sites, it unexpectedly opens a new tab with no data. The code st ...

The JSP AJAX response comes back empty

I am encountering an issue where I am using JQuery Ajax to call a REST API in JSP, but it keeps returning null no matter how I try. Strangely enough, the same code works when used in HTML. I have been searching online for a solution but haven't found ...

The $route.reload() function seems to be ineffective in Internet Explorer

I'm currently using AngularJs to develop an application. The issue I am encountering is related to data not being refreshed in IE, even after executing the $route.reload() function. Strangely enough, this problem only occurs in Internet Explorer and w ...

Lack of post data handling using Ajax, JQuery, Json, and Symfony 2

I have been attempting to send data in json format using JQuery Ajax, but I am unable to receive the posted data in the controller's action. Below is the JQuery/Javascript code snippet: $.ajax({ type: "POST", url: "app_dev.php/aj ...