Exploring the Integration of AngularJS with JSON Arrays

I have been attempting to restructure an existing JSON Array using AngularJS filters like $filter, but unfortunately, I am running into issues.

{
        {       
            name: "name 1",         
            label: "A",     
        },
        {       
            name: "name 2",         
            label: "A",     
        },
        {       
            name: "name 3",         
            label: "B",     
        },
        {       
            name: "name 4",         
            label: "B",     
        },
        {       
            name: "name 5",         
            label: "B",     
        },
        {       
            name: "name 6",         
            label: "C",     
        },
        {       
            name: "name 7",         
            label: "C",     
        },
        {       
            name: "name 8",         
            label: "C",     
        },
        {       
            name: "name 9",         
            label: "D",     
        }
    }

I aim to transform this array into a new one structured as follows.

{
    "A" : { 
        {       
            name: "name 1",         
            label: "A",     
        },
        {       
            name: "name 2",         
            label: "A",     
        },
    },
    "B" : {
        {       
            name: "name 3",         
            label: "B",     
        },
        {       
            name: "name 4",         
            label: "B",     
        },
        {       
            name: "name 5",         
            label: "B",     
        },
    },
    "C" : {
        {       
            name: "name 6",         
            label: "C",     
        },
        {       
            name: "name 7",         
            label: "C",     
        },
        {       
            name: "name 8",         
            label: "C",     
        },
    },
    "D" : {
        {       
            name: "name 9",         
            label: "D",
        }
    }   
}

How can I achieve this restructuring of the array using AngularJS?

Answer №1

One way to achieve this task is by utilizing the lodash library. The _.groupBy function can be used for grouping elements based on a certain criterion:

var groupedArray = _.groupBy(myArray, function(item){
  return item.label;
})

If you only want to extract unique labels from the array, you could use a method like this:

var uniqueLabels = [];
angular.forEach(myArray, function(object){
  if(uniqueLabels.indexOf(object.label) == -1) uniqueLabels.push(object.label)
})

Answer №2

give this a shot

   let output = {}
   angular.forEach(data, function(item){
       if(!output.hasOwnProperty(item.tag) output[item.tag] = []
       output[item.tag].push(item)
   })

   console.log(output)

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 steps can be taken to trigger a function prior to a user closing their browser or tab

What is the best way to trigger a function before the user closes the browser or tab? Here's an example of an ajax request: <script language="JavaScript" type="text/javascript"> function performActionBeforeClose(id) {var xmlhttp; try{ ...

Issue with Angular directive not updating model

Hey there, I've been struggling to update my model using a directive but for some reason it's not working. I'm having trouble figuring out why. Can anyone lend a hand? Here is the HTML code snippet: <input type="file" name="documents" f ...

What is the process for incorporating beforeAnimate and afterAnimate callbacks into a custom jQuery plugin?

Let's imagine I have developed a plugin: // creating the plugin (function($){ $.fn.myPlugIn = function(options){ defaults = { beforeAnimate : function(){}, afterAnimate : function(){} ...

NodeJS npm module installed globally is unable to run the main/bin JavaScript file using node command

Here is an example of my package.json: { "name": "example-module", "version": "1.0.0", "bin": "./bin/example-module.js", "main": "./bin/example-module.js", "description": "Example module description", "homepage": "http://my.home.page.com", " ...

Update a specific HTML element when the result of an equation is modified

I need assistance with my angularjs website development project. I have implemented content-specific tabs, each with its own unique content. When a tab is selected, only the corresponding content should be displayed. The tabs are assigned IDs in the contro ...

unable to connect to the web service using webview

When attempting to call a web service or display an alert, I am encountering some issues: Here is the code from my activity: mWebView = (WebView)findViewById(R.id.webViewRootAciviy); mWebView.setWebViewClient(new WebViewClient()); mWebView.setWebChromeCl ...

How can you trigger a link click event when clicking anywhere on the page using Jquery?

Here's the code I'm working with: <a href="http://google.com" target="_blank">Open in new tab </a> I am trying to make it so that when a user clicks anywhere on the website, the link above will be automatically clicked and a new tab ...

Issue encountered when attempting to batch delete documents within a subcollection: Error message displays "TypeError: n.indexOf is not a

When attempting to batch delete a document within a subcollection, I encounter some issues. There are scenarios where I may need to remove the same product document ID along with various history document IDs, or multiple product document IDs with differen ...

Discover how to capture a clicked word within the Ionic Framework

I've been working on an app using the Ionic Framework. I am trying to figure out how to detect when a word is pressed in my application. One solution I tried involved splitting the string into words and generating a span with a click event for each on ...

Exploring the process of displaying key names and values from JSON decoded data in Laravel Blade

I'm just starting out with Laravel I've created a form where users can input data, which is then saved as a JSON encoded string in the database. Here's the controller code: public function order_requirements(Request $request) { // ...

Function for mapping: Array with nested objects will not be printed one after the other

Looking at the function below, I aim to map _s from res to another function using the return value from the manipulateValidateReqRes function CODE WAS UPDATED BELOW Why am I unable to return _s from the map function on res? It displays an error: TypeError ...

Adding numbered paths to a foreach loop results in transforming a single-dimensional array into a multi-dimensional array

I have developed a function to transform a single dimension array (adjacency list) into a multi-dimensional array. My goal is to include an enumerated path in $aCat. Input (single dimension) [2] => Array ( [id] => 2 [parent_id] ...

Keep the multiselect dropdown list of the select component open

I am currently utilizing the Select component from material-ui-next. Overall, it functions quite smoothly. One scenario where I implement it is within a cell element of an Ag-Grid. Specifically, in this use case, I am making use of the multiselect feature ...

JQuery AJAX not retrieving data after $.post request

I am currently facing a challenge with a specific JQuery $.post request to a PHP-based processor. To troubleshoot, I set up a test page containing the following code: It's important to note that this is hosted on a subdomain, but there are no cross-d ...

Inserting into the center of a JSON object using MySQL

Imagine having JSON data stored in a MySQL database as JSON type: {"key1":"value1","key3":"value3","key2":"value2"} Now, I want to add "key4":"value4" at a specific position within the JSON object, for example: {"key1":"value1", "key4":"value4" ,"ke ...

Gather data from various textboxes and combine them into a unified string with the help of JavaScript

I am currently facing a challenge where I need to extract the values from multiple textboxes and combine them into a single string. This string will then be sent to my PHP processing page for insertion into a database table. The textboxes mentioned above ...

Real-time monitoring within a callback function in Angular 5

I need to ensure that a specific callback is executed only after receiving a response, starting from the line this.groupDefaultExpanded = -1; onwards. loadLoginDetails() { this.derivativeSpecService.getDerivativeDetails().subscribe( res => ...

Using the # symbol alongside other characters or numbers may prevent Reg Ex from validating

I am asking the same question again as I did before. I apologize, but I have checked all the links provided and they were not helpful. Also, this is my first time asking a question here so I was not very clear on how to ask. Here are the details of my iss ...

What is the process of acquiring JSON and converting it into a JavaScript object array?

Can someone please assist me in converting the JSON generated in Spring Boot into a JavaScript object array? I'm currently facing some difficulties. https://i.stack.imgur.com/Tx5Ri.png I've been using XMLHttpRequest and my JS code is as follows ...

Convert user input from an azerty keyboard to Arabic characters automatically using JavaScript

My goal is to create a JavaScript code that can: 1. Accept a character input from a user in an HTML form text field. 2. Retrieve the keyCode of the entered character. 3. Display a corresponding Arabic character based on the acquired KeyCode. For in ...