Tips for displaying nested JSON data in an Angular UI grid

I am working with an Angular UI grid where I need to display data from a nested JSON object. The JSON contains a lot of information, but I only want to show a selected set of properties on the grid. Instead of putting the entire json.Products into the grid, I am looking for a more efficient solution.

HTML:

<div ng-app="exampleApp">
    <section style="width:75%; margin-left:auto; margin-right:auto;" ng-controller="GridController">
    <div id="grid1" ui-grid="gridOptions" class="grid"></div>
    </section>
</div>

JS:

var exampleApp = angular.module('exampleApp', ['ui.grid']);

exampleApp.controller('GridController', ['$scope', function ($scope) {
    $scope.gridOptions = {
        paginationPageSizes: [15, 25, 50, 75],
        paginationPageSize: 15,
        enableSorting: true,
        showGridFooter: true,
        columnDefs: [
            { field: 'Products.ProductCode', name: 'Products.ProductCode', width: '200', displayName: 'PRODUCT CODE'},
            { field: 'Products.ProductName', name: 'Products.ProductName', displayName: 'PRODUCT NAME'}
        ],

        onRegisterApi: function(gridApi) {
                $scope.gridApi = gridApi;
        }
    };

  var sResult = JSON.stringify(gridData);
  var parsedResult = JSON.parse(sResult);
  $scope.AllProductData = parsedResult;
  $scope.productData = parsedResult.Products;
  $scope.gridOptions.data = $scope.AllProductData;
  console.log("AllProductData: " + JSON.stringify($scope.AllProductData));
}]);

var gridData = [{
    "Products": [{
        "RecordType": "012d0000000xBIOAA2",
        "QuantityFlag": "Green",
        "QuantityAvailable": null,
        "ProductName": "10 Pin Connector, Digital Board",
        "ProductId": "01td0000001skXZAAY",
        "ProductCode": "7149",
        "PricebookEntryId": "01ud0000005tOgzAAE",
        "IsSelected": false,
        "IsCommonItem": false,
        "Active": true
    }, {
        "RecordType": "012d0000000xBIOAA2",
        "QuantityFlag": "Green",
        "QuantityAvailable": null,
        "ProductName": "10 Prepaid worm",
        "ProductId": "01td0000001sks9AAA",
        "ProductCode": "805514-PPD",
        "PricebookEntryId": "01ud0000005tLZHAA2",
        "IsSelected": false,
        "IsCommonItem": false,
        "Active": true
    }, {
        "RecordType": "012d0000000xBIOAA2",
        "QuantityFlag": "Red",
        "QuantityAvailable": 0,
        "ProductName": "10x1 ITALIAN DIAGNOSTIC KIT",
        "ProductId": "01td0000001sl03AAA",
        "ProductCode": "902232-ITA",
        "PricebookEntryId": "01ud0000005tP99AAE",
        "IsSelected": false,
        "IsCommonItem": false,
        "Active": true
    }, {
        "RecordType": "012d0000000xBIOAA2",
        "QuantityFlag": "Red",
        "QuantityAvailable": 0,
        "ProductName": "10x1 SPAIN DIAGNOSTIC KIT",
        "ProductId": "01td0000001sl0KAAQ",
        "ProductCode": "902232-SPN",
        "PricebookEntryId": "01ud0000005tPENAA2",
        "IsSelected": false,
        "IsCommonItem": false,
        "Active": true
    }],
    "CustomerId": "006q0000007KyVnAAK",
    "AccountId": "1035620"
}];

Refer to FIDDLE

Check out the Updated Fiddle which demonstrates the grid working with the account ID but not the nested products. This fiddle explains why I prefer not to use something like

$scope.gridOptions.data = grid[0].products;

If there is a solution that allows me to change the property products.IsSelected to True without looping and preserving the JSON structure, please advise. I aim to ensure that gridData.Products still references the original gridData.

Answer №1

Tested on Fiddle.

var exampleApp = angular.module('exampleApp', ['ui.grid']);

//The grid in this example would display a list of products where users can select and add them to a cart. The IsSelected property will be set to true.
exampleApp.controller('GridController', ['$scope', function ($scope) {
$scope.gridOptions = {
    paginationPageSizes: [15, 25, 50, 75],
    paginationPageSize: 15,
    enableSorting: true,
    showGridFooter: true,
    columnDefs: [
        { field: 'ProductCode', name: 'Products.ProductCode', width: '200', displayName: 'PRODUCT CODE'},
        { field: 'ProductName', name: 'Products.ProductName', displayName: 'PRODUCT NAME'}
    ],

    onRegisterApi: function(gridApi) {
            $scope.gridApi = gridApi;
    }
};

 $scope.gridOptions.data = gridData[0].Products;
}]);

//Users can modify quantity and other properties for items in their cart and then proceed to checkout, which will send all data back to the server.

 /*
I prefer not to use:
 $scope.gridOptions.data: gridData.Products;
 as I need to send all the received data back to the server in my ajax call.
 The grid should only retrieve what it needs from the JSON data.
*/

 var gridData = [{
"Products": [{
    "RecordType": "012d0000000xBIOAA2",
    "QuantityFlag": "Green",
    "QuantityAvailable": null,
    "ProductName": "10 Pin Connector, Digital Board",
    "ProductId": "01td0000001skXZAAY",
    "ProductCode": "7149",
    "PricebookEntryId": "01ud0000005tOgzAAE",
    "IsSelected": false,
    "IsCommonItem": false,
    "Active": true
}, {
    "RecordType": "012d0000000xBIOAA2",
    "QuantityFlag": "Green",
    "QuantityAvailable": null,
    "ProductName": "10 Prepaid worm",
    "ProductId": "01td0000001sks9AAA",
    "ProductCode": "805514-PPD",
    "PricebookEntryId": "01ud0000005tLZHAA2",
    "IsSelected": false,
    "IsCommonItem": false,
    "Active": true
}, {
    "RecordType": "012d0000000xBIOAA2",
    "QuantityFlag": "Red",
    "QuantityAvailable": 0,
    "ProductName": "10x1 ITALIAN DIAGNOSTIC KIT",
    "ProductId": "01td0000001sl03AAA",
    "ProductCode": "902232-ITA",
    "PricebookEntryId": "01ud0000005tP99AAE",
    "IsSelected": false,
    "IsCommonItem": false,
    "Active": true
}, {
    "RecordType": "012d0000000xBIOAA2",
    "QuantityFlag": "Red",
    "QuantityAvailable": 0,
    "ProductName": "10x1 SPAIN DIAGNOSTIC KIT",
    "ProductId": "01td0000001sl0KAAQ",
    "ProductCode": "902232-SPN",
    "PricebookEntryId": "01ud0000005tPENAA2",
    "IsSelected": false,
    "IsCommonItem": false,
    "Active": true
}],
"CustomerId": "006q0000007KyVnAAK",
"AccountId": "1035620"
}];

This example only manipulates the products within the gridData object, not the object itself. This way, the necessary product data can be sent back to the server. Additional clarification may be needed if further requirements arise.

Answer №2

After conducting some experimentation, I discovered that the nested products within the json object actually retain a connection to the original data. I was under the impression that gridData.Products was a separate copy, but I now realize that changes made to gridData can directly impact gridData.Products. I mistakenly thought I needed to iterate through each product in gridData to modify it individually, but that was not the case.

In conclusion, disregard my initial question.

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

Error code EPERM encountered while attempting to append a file on a network

An issue arises when the application is required to store log data on a network drive. While everything works smoothly when the drive is hosted under Windows, complications arise when it is hosted on a Mac. Read/write operations function properly, but appe ...

Filtering in AngularJS can be done based on the comma-separated elements

I am trying to implement a filter in AngularJS for a specific JSON format value [ {"id":"1","video_title":"Sample1","tags":"2,12,13","featured":"1"}, {"id":"2","video_title":"Sample2","tags":"5,13","featured":"1"}, {"id":"2","video_title":"Sample3","ta ...

Model Abstracted Aurelia Validation

I recently completed an online course on Aurelia by Scott Allen where he introduced the Aurelia-Validation plugin for form validation. As a result, my view-model now looks like this in edit.js: import {inject} from "aurelia-framework"; import {MovieServi ...

Determine in JavaScript whether a character is 32-bit or not

Is there a way to determine if a specific character is 32 bits using JavaScript? I attempted to use charCodeAt() but it was unsuccessful for identifying 32-bit characters. Any guidance or assistance on this matter would be greatly valued. ...

Utilize the converse.js plugin to set up a secure room with password protection

I'm looking to set up a password-protected room. Currently, I can create a public room and add a password in the configuration settings. However, I have to start by creating an unsecured, public room first. Is there a way to create a room with a pas ...

Display an alert when no matches are found in autocomplete suggestions

I am implementing the code below to populate a textbox with data. If I input a, all records starting with a are displayed in the dropdown from the database. However, if I input a value that does not exist in the database, there is no message like "No Recor ...

Is there a way to programmatically click on a link within the first [td] element based on the status of the last [td] element in the same [tr] using codeceptjs/javascript?

The anticipated outcome: Pick a random assignment from the table that has the status "Not start". Below is the table provided: <table id="table1"> <tbody> <tr class="odd1"> <td> < ...

Executing a scroll down action with Selenium in combination with Node.js and the Chai/Mocha testing framework

Browser: Chrome Looking for ways to scroll up or down using Selenium with Node.js (JavaScript). ...

The content within the hyperlinked text

<ul class="Buttons"> <li><a href="#" onclick="myFunc(); return false;">Accept</a></li> <li><a href="#" onclick="myFunc(); return false;">Reject</a></li> <li><a href="#" onclick="myF ...

What is the best way to dynamically add data to a JSON file?

image of JSON file Just a heads up: I'm looking to add data directly without the need to write it to a .json file, perhaps by using Angularfire2 database. user = { name: 'Arthur', age: 21 }; const options = {Headers, responseType: &apo ...

What exactly is the function of registerServiceWorker in React JS?

Just starting out with React and I have a question about the function of registerServiceWorker() in this code snippet: import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import registerServi ...

What is the best way to retrieve ember model relation properties within routes and controllers?

Currently using ember 2.7.0, I am facing an issue while setting up my ember app with a currentUser.organization derived from the authenticated token. Although I can successfully resolve the currentUser, I am encountering difficulties in resolving the prope ...

What steps should I take to establish routes in my node and express application that allow for authentication through a designated method?

Currently, I am following the backend set up tutorial from auth0, and I have a question regarding how to organize my routes in a separate file rather than in the app.js. In the tutorial, they demonstrate var authenticate = jwt({ secret: new Buffer(proc ...

Leveraging Angular directives in pure HTML within jQuery

After receiving an AJAX response, I am dynamically generating HTML code. Here is an example of what I am doing: var html = ''; html = '<div ng-click="deleteRecord($event)">delete</delete>'; $('.main).append(html); Ho ...

Error in AngularJS ng-repeat syntax

As a newcomer to AngularJS, I ventured into creating a Bootstrap form with a loop but encountered an error. What could be the mistake I made? <form class="form-horizontal" role="form" name="newForm" novalidate ng-controller="newFormController"> < ...

The price filter slider is experiencing issues with the onresize function not functioning properly

I am facing an issue with a price filter I developed for my project. Despite having coded it, the filter is not functioning properly. <div class="price_range_caption"> <span class="currency_from">Rs.</span><span id="price_range_f ...

Parsing JSON with Spray JSON when it uses snake case (underscore notation) rather than camel case: a step-by-step guide

Is there a way to properly parse JSON using spray json when it is formatted in snake case (underscore notation) instead of camel case? For example: case class Test(subjectDescription: String) "{\"subject_description\":\"Medicine\"}".p ...

Arrange a QJsonArray in a particular order

Let's say there is a function with the following signature: bool sortJson(QJsonArray &); The purpose of this function is to sort the QJsonArray and return true only if all members are of type double. One way to achieve this is by creating an aux ...

Activate a monitoring pixel with a click of your mouse

I have a tracking pixel that is typically placed in the body of a "installation success" page: <img src="http://domain.com/adclick.php" width="1" height="1" border="0" /> However, I want to trigger this pixel when someone clicks on a download butto ...

Tips for keeping a login session active on multiple tabs

As I am in the process of developing a website, one issue I am facing is determining the most effective method to maintain user login sessions. Currently, I am utilizing Html5 web storage known as "session storage" to keep track of whether a user is logged ...