Convert a JSON Object using AngularJs

Is there a method in Angular to restructure this JSON Object? I am looking to convert the JSON object from its original format:

    $scope.TestJson = {
        "filters": [
                {
                    "dataPropertyID": "VoidType",
                    "label": "Homeless"
                },
                {
                    "dataPropertyID": "VoidType",
                    "label": "Mainstream"
                },
                {
                    "dataPropertyID": "PropertyType",
                    "label": "Flat"
                },
                {
                    "dataPropertyID": "PropertyType",
                    "label": "Cottage"
                }
        ]
    }

To the following structure:

    $scope.NewTestJson = {
        "filters": [
                {
                    "dataPropertyID": "VoidType",
                    "label":[ "Homeless","Mainstream"]
                },
                {
                    "dataPropertyID": "PropertyType",
                    "label":[ "Flat", "Cottage"]
                }
        ]
    }

Answer №1

This particular issue seems to be more geared towards JavaScript rather than anything else. However, here is a possible solution:

$scope.NewTestJson = {
    filters: [];
};

// Iterate through all existing filter items
$scope.TestJson.filters.forEach(function(filter) {
    // Check if the new filter already exists
    var newFilter = $scope.NewTestJson.filters.filter(function(newFilter) {
        return newFilter.dataPropertyID === filter.dataPropertyID;
    }).shift();

    // Create the new filter if it doesn't exist
    if (!newFilter) {
        newFilter = {
            dataPropertyID: filter.dataPropertyID,
            label: []
        };
        $scope.NewTestJson.filters.push(newFilter);
    }

    // Add the old filter label to the new filter
    newFilter.label.push(filter.label);
});

Answer №2

const jsonData = {
        "filters": [
                {
                    "dataPropertyID": "VoidType",
                    "label": "Homeless"
                },
                {
                    "dataPropertyID": "VoidType",
                    "label": "Mainstream"
                },
                {
                    "dataPropertyID": "PropertyType",
                    "label": "Flat"
                },
                {
                    "dataPropertyID": "PropertyType",
                    "label": "Cottage"
                }
        ]
    };

const newJsonData = new Object();
newJsonData.filters = new Array();


for (let element in jsonData.filters) {
    let check = 0;
    for (let elem in newJsonData.filters) {
        if (jsonData.filters[element].dataPropertyID === newJsonData.filters[elem].dataPropertyID) {
            newJsonData.filters[elem].label.push(jsonData.filters[element].label);
            check = 1;
        }
    }
    if (check == 0) {
        const newObj = new Object();
        newObj.dataPropertyID = jsonData.filters[element].dataPropertyID;
        newObj.label = new Array();
        newObj.label.push(jsonData.filters[element].label);
        newJsonData.filters.push(newObj);
    }
}

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

Prevent Rails from attempting to generate a template error with ActionView::MissingTemplate

Currently, I am working on setting up a basic Angular Rails application. Below is the code for my rails controller: class ItemsController < ApplicationController respond_to :json, :html def index @items = Item.order(params[:sort]).page(params ...

How can you set the listbox in Sumo Select to always be open?

https://i.sstatic.net/fkiHB.png Is there a way to ensure the listbox is always open by default, as if the user had clicked? ...

Attempting to prevent the use of the <p> tag solely before the text

My toggle function is not working correctly in my FaQ section. When a user clicks on a topic, the bottom section should appear, but the <p> tag is being displayed across the entire line instead of just one word.. Here is an image to help illustrate ...

How can I trace the origin of a post request sent from a form?

When constructing an HTML form, I typically utilize <form action="/postRoute" method="post"> to submit a post request. However, while examining a form for which I needed the post request URL, I came across the following: <form action="index.cf ...

Forge: Securely encrypting massive files

I rely on the forge framework for implementing PGP functionality, specifically for encrypting large files (2gb or larger) while minimizing RAM usage. What would be the most efficient approach to achieve this? ...

angular2 ngFor is not functioning properly

I'm having an issue where I cannot get textboxes to appear whenever a user clicks a button. I am attempting to achieve this using ngFor, but for some reason, the ngFor is not iterating as expected. Even after trying to change the array reference with ...

How can I change JSON to an array using Jquery?

Snippet var jsonData = '{"Error":"Only alphabet characters and spaces are allowed in the name"}'; try { // Parsing JSON string into a JavaScript array var dataArr = $.parseJSON(jsonData); // Iterating through the array for (let key i ...

An unexpected error occurred: [$injector:modulerr] ngAnimate AngularJS 1.2

Upon running my application, I encountered an Uncaught Error: [$injector:modulerr]. It seems that with the update to version 1.2 of AngularJS, certain functionalities have been removed from the core. I have downloaded angular-animate.js and all other exter ...

Tips for maintaining a healthy balance of tasks in libuv during IO operations

Utilizing Typescript and libuv for IO operations is crucial. In my current situation, I am generating a fingerprint hash of a particular file. Let's say the input file size is approximately 1TB. To obtain the file's fingerprint, one method involv ...

Showing headings in the table vertically

I have a header1 and header2 with corresponding data1 and data2 that I want to display differently. h h e e a a d d e e r r 1 2 data1 data2 To enhance the presentation, I wish to add borders around the head ...

The parameters remain consistent across all Angular directives

I have created a directive called 'filterComponent' with the following code: app.directive('filterComponent', function() { return { restrict: 'E', templateUrl: 'filter-component.html', link: function ...

How can we transfer data using Routes in React applications?

In my React application, I have a datatable that opens an "Add New" page (a reusable form) when the user clicks on the corresponding button. This AddNew page reads form fields (employeeInputs) specified in App.js. import { employeeInputs } from "./formSour ...

Dynamically enhance the JSON root with additional value

Oh dear, I'm feeling quite perplexed right now. I created a JSON element in the following way: var planet = {"continent": []}; planet.continent.push({name: "Asia", flag: "yes", countries: []}); planet.continent[0].countries.push({name: "Japan", capi ...

Encountering an error stating 'ReadableStream is not defined' while attempting to log in using Discord on the NextAuth application

While attempting to set up a Discord sign-in page to test NextAuth on my website, I encountered the error ReferenceError: ReadableStream is not defined. After examining the stack trace, it seems to be related to how my packages are configured, but I' ...

Error loading Azure Active Directory web form: Server returned a 401 status code for the requested resource

I recently made changes to my web site (incorporating a web form and entity framework) to use AAD connection, following the guidance in this insightful blog post. However, I am encountering an issue where scripts and css files are not loading properly. Th ...

React Hook is failing to trigger an update

Learning React and JavaScript has been quite a challenge for me, especially when it comes to understanding React Hooks and the issue of them not updating sometimes. I have tried searching online but either end up with solutions for class-based components o ...

Exploring the power of Cucumber, Ruby, Capybara, and Selenium: Enhancing the 'visit' method to handle dynamic content delays

For weeks now, I've been dealing with an issue that seems to have no solution found online... like waiting for ajax, etc... Check out the versions of gems: capybara (2.10.1, 2.7.1) selenium-webdriver (3.0.1, 3.0.0) rspec (3.5.0) running ruby 2.2.5 ...

Make sure to assign an id to the ng-template when using an Angular Bootstrap accordion

I'm struggling to assign a dynamic id to the heading template. I attempted to use id="{{group.title}}" but it doesn't seem to be working. Any assistance or suggestions would be greatly appreciated! <div ng-controller="AccordionDe ...

Guide on redirecting a webpage post form validation in JavaScript

I have a question about my JavaScript code. Even if validation fails, the contact us page still appears. How can I fix this issue? Appreciate any help. Thank you! (function () { window.addEventListener('load', function () { var forms = do ...

Tips on updating the default checkbox dynamically based on the current checkbox using JavaScript

Seeking to enhance the design of a Perl-generated form with custom CSS effects, rather than relying on the default Perl form. Despite successful functionality, encountering an issue where radio button focus reverts to default selection (Date) after submitt ...