AngularJS retrieve data from JSON (like using MySQL)

My data is in JSON format:

{"sectionTitle":"Account Information","sectionItems":[{"itemTitle":"Balance","url":"/account/balance","selected":true},{"itemTitle":"Account Statement","url":"/account/statementsearch","selected":false},{"itemTitle":"Deposit","url":"/account/deposit","selected":false},{"itemTitle":"Withdrawal","url":"/account/withdraw","selected":false},{"itemTitle":"Edit Profile","url":"/account/editprofile","selected":false},{"itemTitle":"Change Password","url":"/account/changepassword","selected":false}]}

Is there a way to check if any child item within the sectionTitle has selected set to true?

Similar to this SQL query:

SELECT * FROM sectionItems WHERE selected=true

Can I achieve something similar using AngularJS to determine if the parent has children?

I hope my question makes sense.

This is the HTML snippet I'm working with:

           
<nav class="sidebar-nav">
    <ul class="nav metismenu" id="side-menu-help">

        <li ng-repeat="menuItem in accountCtrl.menuStructure">
            <a class="{{ (menuItem.sectionItems.length > 0) ? 'metisHasChildren' : '' }}" href="/en/help-area/poker-help/poker-rules/">
                <span ng-if="menuItem.sectionItems.length > 0" class="fa arrow fa fa-angle-double-down"></span>
                {{ ::menuItem.sectionTitle }}
                {{ ::menuItem }}
            </a>
            <ul class="nav nav-second-level collapse in">
                <li ng-repeat="subMenuItem in menuItem.sectionItems" ng-click="accountCtrl.changePage(subMenuItem.url)">
                    <a ng-class="(subMenuItem.selected) ? 'page-active' : ''">{{ ::subMenuItem.itemTitle }}</a>
                </li>
            </ul>
        </li>

    </ul>
</nav>

Answer №1

Getting this to work doesn't require any fancy tricks. Just convert the json into an object and then access the desired property using dot notation. Here's a simple example:

var jsonData      = JSON.parse(json);
var selectedItems = [];

angular.forEach(jsonData.sectionItems, function(item) {
    if (item.selected) {
        selectedItems.push(item);
    }
});

This code snippet will convert the json string into an object, loop through each child sectionItem, check if selected is true, and build an array of matching items.

Answer №2

If you're looking to filter out specific sectionItems based on a condition, consider using a forEach loop. In this example, we are creating an array of sectionItems where the 'selected' property is true, but feel free to adjust it as needed.

$scope.items =[];
angular.forEach(sectionItems, function(item){
  if (item.selected === true){
    $scope.items.push(item);
  }
})

UPDATE

For a demonstration, check out this functioning plunk

To integrate this filtering technique seamlessly with ng-repeat, utilize it within a custom filter like so:

app.filter('menuFilter', function() {

  return function(menuItems) {
    var filtered = [];

    angular.forEach(menuItems, function(menuItem) {
      angular.forEach(menuItem.sectionItems, function(item) {
        if (item.selected === true) {
          filtered.push(menuItem);
        }
      });
    });

    return filtered;
  }
});

Finally, update your markup in this way:

ng-repeat="menuItem in accountCtrl.menuStructure | menuFilter "

Answer №3

Start by utilizing the standard filter without the need for a custom filter:

<li ng-repeat="menuItem in accountCtrl.menuStructure | filter: { sectionItems: { selected: true } }"> {{ menuItem.sectionTitle }}

Demo of this implementation:

angular.module('app', [])
  .controller('accountController', function() {
    var vm = this;
  
    vm.menuStructure = [  
       {  
          "sectionTitle":"Account Information",
          "sectionItems":[  
             {  
                "itemTitle":"Balance",
                "url":"/account/balance",
                "selected":true
             },
             {  
                "itemTitle":"Account Statement",
                "url":"/account/statementsearch",
                "selected":false
             },
             {  
                "itemTitle":"Deposit",
                "url":"/account/deposit",
                "selected":false
             },
             {  
                "itemTitle":"Withdrawal",
                "url":"/account/withdraw",
                "selected":false
             },
             {  
                "itemTitle":"Edit Profile",
                "url":"/account/editprofile",
                "selected":false
             },
             {  
                "itemTitle":"Change Password",
                "url":"/account/changepassword",
                "selected":false
             }
          ]
       },
       {  
          "sectionTitle":"Account Information 2",
          "sectionItems":[  
             {  
                "itemTitle":"Balance",
                "url":"/account/balance",
                "selected":false
             },
             {  
                "itemTitle":"Account Statement",
                "url":"/account/statementsearch",
                "selected":false
             },
             {  
                "itemTitle":"Deposit",
                "url":"/account/deposit",
                "selected":false
             },
             {  
                "itemTitle":"Withdrawal",
                "url":"/account/withdraw",
                "selected":false
             },
             {  
                "itemTitle":"Edit Profile",
                "url":"/account/editprofile",
                "selected":false
             },
             {  
                "itemTitle":"Change Password",
                "url":"/account/changepassword",
                "selected":false
             }
          ]
       }
    ];
  });
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>

<body ng-controller="accountController as accountCtrl">
  <ul>
    <li ng-repeat="menuItem in accountCtrl.menuStructure | filter: { sectionItems: { selected: true } }"> {{ menuItem.sectionTitle }}
      <ul class="nav nav-second-level collapse in">
        <li ng-repeat="subMenuItem in menuItem.sectionItems" ng-click="accountCtrl.changePage(subMenuItem.url)">
          <a ng-class="{ 'page-active': subMenuItem.selected }" ng-bind="::subMenuItem.itemTitle"></a>
        </li>
      </ul>
    </li>
  </ul>
</body>

</html>

Suggestions:

  1. Instead of using ngClass with ternary operator, you can simply use this approach:
ng-class="{ 'page-active': subMenuItem.selected }"
  1. While your current method works fine, consider exploring the special-repeats feature which may be more suitable for your scenario.

I trust this information proves useful!

Answer №4

let data = [{"sectionTitle":"Account Information","sectionItems":[{"itemTitle":"Balance","url":"/account/balance","selected":true},{"itemTitle":"Account Statement","url":"/account/statementsearch","selected":false},{"itemTitle":"Deposit","url":"/account/deposit","selected":false},{"itemTitle":"Withdrawal","url":"/account/withdraw","selected":false},{"itemTitle":"Edit Profile","url":"/account/editprofile","selected":false},{"itemTitle":"Change Password","url":"/account/changepassword","selected":false}]}];
let selectedItems = data.filter(item => item.sectionItems.some(subItem => subItem.selected));

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

A Bluebird promise was generated within a NodeJS handler function, however it was not properly returned from the function

Below is the nodejs code for an express middleware function: Middleware.is_authenticated = function(req, res, next) { if(req.system_session == undefined || req.system_session.login_status == false) return res.status(401).send({errors: true, error: &ap ...

Text displaying as actionable icons

In my React project, I am utilizing material-table (https://material-table.com/#/) and have successfully imported the necessary icons. However, when viewing the action bar, the icons are displaying as plain text instead of the Material Icon. import React, ...

Utilizing Laravel's leftJoin method to link and access related elements

I currently have two tables in my database set up like this: connections id owner_id owners id first_name ConnectionsController.php $connections = DB::table('connections') ->leftJoin('owners', 'own ...

Update the value of a JavaScript variable in an HTML template by targeting the element with a specific

Within my testFile.html HTML file, the following code is present: <div id="image-type-placeholder">marinaa</div> In my JavaScript file: const CourseImageUpload = BaseComponent.extend({ /** * @property {function} */ templat ...

Incomplete Json information

As I embark on my journey to learn Javascript and work on building an application simultaneously, I can't help but feel optimistic about the learning process. To guide me through this venture, I've turned to the teachings of Alex MacCaw in his bo ...

Obtain offspring from a parent element using jQuery

$(document).ready(function() { $.ajax({ type: "POST", url: 'some/url', data: { 'name':'myname' }, success: function (result) { var result = ["st ...

Issues with Angular $resource not being functional in Internet Explorer version 11

Utilizing angular, I am making a request to my controller in MVC using $resource. However, I've encountered an issue where it doesn't function properly in IE11, although it works fine in Chrome and Firefox. Within my homeController.js, this $sco ...

Organizer featuring Outlook-inspired capabilities

My goal is to develop a system for efficiently managing appointments. Upon opening the application, I want to display a calendar control that will retrieve an individual's schedule from a SQL server database. For example, if the user has meetings sch ...

Using typecasting method to extract value from a JSON object

Struggling with a JavaScript and JSON issue. There's a function that includes a JSON object: blah=function(i){ var hash= ({ "foo" : "bar", "eggs":"bacon", "sausage":"maple syrup" }); var j=eval(hash); // Convert to Object console.log(j.toSou ...

PHP - Extract Information from Table Upon Form Submission without User Input

I'm facing a challenge with my web form that includes a table allowing users to delete rows before submitting. Although there are no input fields in the table, I need to capture the data from these rows when the form is submitted. The issue is that th ...

When encountering a 404 redirect, CSS and JS files may fail to display

I created a unique error message using .htaccess, incorporating CSS and JS in separate folders. Although it functions properly when accessed directly, integrating these resources into the 404 Error message results in only the HTML text being displayed with ...

Can qTip 2.0 be configured to use a different default attribute instead of 'title'?

Is there a way to set qTip to use an attribute other than 'title' as the default? I need to use another attribute because when I disable qtip and add elements dynamically with "title", the title still shows when I hover over the element, which i ...

Unable to access JSON data from LocalStorage using jQuery

Currently, I am encountering an issue while attempting to save a JSON array in jQuery to localStorage for future use. Unexpectedly, whenever I make the attempt to save it, an error indicating that the object is not defined arises. Below is my present code: ...

Looping through JSON results in PHP

Trying to work with a JSON file called 'extract.json' and loop through the results in my code, but it seems to only be returning one row. Here is my script: $filename = "extract.json"; $str = file_get_contents($filename); if($str!=null) { $ ...

Is it possible to activate the :active pseudoclass by pressing the 'enter' key on the keyboard using solely CSS?

The CSS: a:focus { opacity: .75 } a:active { transform: translateY(4px) } The purpose: When keyboard users tab to the link, the :focus style serves as a visual indicator Upon pressing the enter key to activate the link, the :active style provides ...

Steps to turn off the automatic completion feature for orders in WooCommerce on your WordPress website

Looking for assistance with changing the order status from completed to processing. When an order is placed, it automatically goes to completed status which is not the desired outcome. The status should change based on the virtual product purchased. I wou ...

What is the best way to establish a limit on the number of characters that can be entered into an input field in a React form?

Currently, I am creating a tool to check the strength of passwords based on their length. However, I am unsure of how to precisely determine if a password falls within specific length ranges such as "between 5 and 10 characters" or "between 20 and 30 cha ...

Guide to creating targeted requests with Wiremock

Working on simulating mock data with Wiremock, I am sending a JSON body request as follows: {"petId ":"123"} For petIds 123, 124, and 125, the expected response should be: {"petType":"1", "wildLevel":"40"} For petIds 250, 251, and 252, {"petTyp ...

Dealing with errors such as "Failed to load chunk" can be resolved by implementing lazy-loading and code-splitting techniques

Our team is currently working on a Vue.js application using Vue CLI 3, Vue Router, and Webpack. The routes are lazy-loaded and the chunk file names include a hash for cache busting purposes. So far, everything has been running smoothly. However, we encoun ...

What is the best way to import JSON functionality into Javascript specifically for use with Internet Explorer

I am facing an issue with loading JSON feature in JavaScript for IE8 while in compatibility mode. After receiving advice, I decided to utilize douglascrockford/JSON-js to enable JSON support on outdated browsers. To tackle this problem, I created a new f ...