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

Using Javascript with the Google Calendar API: How can I swiftly make a new event with the Quick Add feature?

Currently, I am exploring the Google Calendar API and struggling with implementing a Quick Add Event using javascript. Is it possible to achieve this task? Are there any resources or examples that can help me understand how to do it? My issue lies in the ...

When integrating React with Tawk, the user's name and email are automatically encoded before being sent

My code within the componentDidMount() function initializes a widget popup when the page loads. It then sets the name and email using parameters received from the previous page. const fullName = this.state.data[0]; console.log(fullName); const e ...

Enhance parent style when child's data-state or aria-checked attributes are updated in React using Styled Components

Within a label, there is a button embedded as shown below: <MyLabel htmlFor='xx' onClick={() => onChange}> <MyButton id='xx' {...rest} /> Check it! </MyLabel> In the Developer Tools Elements section, the st ...

Exploring the world with an interactive map in R, incorporating Shiny and leaflet

I'm currently attempting to integrate a Google layer as the base layer for a Leaflet map in Shiny R. To achieve this, I've been utilizing shinyJs to inject a JavaScript script into my R code and add the map. However, I'm facing an issue wher ...

Why is it that the edit or delete button is not functioning when I attempt to click on the next page?

Having an issue with my script. It works fine for editing and deleting on the first page, but when I navigate to the next page, those functionalities stop working. Can anyone help me troubleshoot this problem? <script> $(function(){ $(&ap ...

Conceal a request URL within JavaScript through the use of Laravel/Ajax

I have an idea that I'm not sure is great or even feasible, but I really need to make it work. I am attempting to obfuscate a URL that needs to be used in a Javascript function as a parameter. This is what I currently have: <script> myFunction ...

What is the reason Node.js only prints one item at a time?

Currently, I am using node.js to extract items from a text file. Right now, the code prints out the items in the terminal, but I want it to be able to accept multiple parameters and print each of them individually instead of just the last one. // Checki ...

Tips for sending a successful POST request with the MEAN stack

Currently, I am utilizing yeoman to set up a new project. My ultimate goal is to master the process of scaffolding CRUD operations. However, I have encountered an issue with a post request. For this reason, I opted for the angular-fullstack generator as I ...

The resize function fails to trigger when it is required

Struggling to get this code working properly. If the window width is greater than 800, I want 6 images with a red background. If the window width is less than 800, I want 4 images with a blue background. I need this functionality to work both on r ...

Tips for triggering a click event on a DOM element using Angular 2

How can I automatically load a component upon loading? <app-main id="tasks" [(ngModel)]="tasks"></app-main> Here is the function call from JavaScript: public tasks; ngOnInit() { this.tasks.click(); } I have attempted using document.getE ...

Guide to creating a rising or waving effect for text using CSS or JavaScript without the need for animation

Is there a way to style dynamic text like this using HTML? I'm open to using CSS or Javascript, as long as it does not involve animation. ...

Creating an installation package for an Electron application on Windows

Is it possible to create a Mac installer for an Electron app using a Windows PC? I have tried running npm make, but it only generates a Windows installer. ...

A helpful tutorial on replacing a link with a Hyperlink containing the text "Click here," using a string from a static JSON in an Android application

{ "json_pos": "11", "beach_name": "Kee (Haena State Park)", "direction": "N", "code_name": "Lifeguarded", "pin": "pingreen", "about": "ALERT: Haena State Park is currently closed due to recent floods. More information can be found at the offici ...

Activate a jQuery collapsible feature through an external hyperlink

Can we enable the expansion of a jQuery collapse by clicking on an external link? For instance, let's say we have a link on the home page that leads to another page. When the user clicks on this link from the home page, we want it to redirect to the i ...

Transform YAML into JSON with no need for a specific structure

Services: - Orders: - ID: $save ID1 SupplierOrderCode: $SupplierOrderCode - ID: $save ID2 SupplierOrderCode: 111111 I am facing a challenge while trying to convert a dynamic YAML string to JSON format. Since the source data ...

Generate table rows by automatically summing the rows and column data using a loop

I'm currently working on a form that dynamically adds data to columns and rows. While I've successfully generated the column names based on database data and used a loop to add details, adding rows has proved to be quite challenging :) Is ther ...

Defining JSON Schema for an array containing tuples

Any assistance is greatly appreciated. I'm a newcomer to JSON and JSON schema. I attempted to create a JSON schema for an array of tuples but it's not validating multiple records like a loop for all similar types of tuples. Below is a JSON sampl ...

Replace character within a table using jQuery

Below is the table content: <table> <tr> <td>"James"</td> <td>"do"</td> <td>"you</td> <td>"like</td> <td>"your life"</td> </tr> </table> <butt ...

Having trouble resolving errors in Visual Studio Code after failing to properly close a parent function? Learn how to fix this issue

Here we have the code starting with the construct function followed by the parents function public construct() //child { super.construct; } protected construct() //parent { } The issue arises where I am not receiving an er ...

Allowing the contenteditable attribute to function only on a single line of

My app allows users to create different lists, with the ability to edit the name. However, I am facing an issue where if a user types a new name, it should remain on only one line. I tried adding max height and overflow hidden properties, but it only hides ...