Iterate over a JSON array in Angular JS using a loop

My goal is to iterate through an array from JSON and format the contents into a side menu display. Here's the code snippet I created:

<ul ng-repeat="(key, value) in menuList.Menu">
  <li>{{key}}</li>
  <ul ng-repeat="(key, value) in value">
    <li> {{key}}</li>  //second key
    <ul ng-repeat="(key, value) in value">
      <li> {{key}}</li> 
      <ul ng-repeat="(key, value) in value">
        <li> {{key}} : {{value}}</li>  
      </ul>
    </ul>
  </ul>
</ul>

The issue I'm facing is that my second key contains both an object and an array. I need to figure out how to display the value of the object and only loop/ng-repeat through the array without displaying its entire content.

 <li> {{key}} : {{value}}</li>  

Here is a snippet of my JSON data for better understanding:

{
  "class": 99,
  "mode" : 0,
  "Menu": [{
      "MenuNum":  1,
      "MenuItems":  [{
          "ItemNum":  0,
          "ItemDesc": "Main Menu",
          "ActionCode": "-",
          "ActionInst": ""
        } , {
          "ItemNum":  1,
          "ItemDesc": "BBQ",
          "ActionCode": "M",
          "ActionInst": "0992"
        }, {
          "ItemNum":  2,
          "ItemDesc": "Beverages",
          "ActionCode": "M",
          "ActionInst": "0992"
        }]
        },{
      "MenuNum":  2,
      "MenuItems":  [{
          "ItemNum":  0,
          "ItemDesc": "Sub Menu",
          "ActionCode": "-",
          "ActionInst": ""
        }, {
          "ItemNum":  1,
          "ItemDesc": "BBQTYPE1",
          "ActionCode": "P",
          "ActionInst": "0996"
        }, {
          "ItemNum":  2,
          "ItemDesc": "BeveragesTYPE1",
          "ActionCode": "P",
          "ActionInst": "0998"
      }]
  }]
}

I envision the sidebar looking more like this:

Answer №1

Assuming that you are interested in implementing ng-repeat logic, the following code snippet could fulfill your requirements:

  <ul ng-repeat="topMenu in menuList.Menu">
        <li>
            {{$index}}
        <ul>
            <li>
                MenuNum: {{topMenu.MenuNum}}
            </li>
            <li> MenuItems
                <ul ng-repeat="submenu1 in topMenu.MenuItems">
                    <li>
                        {{$index}}
                        <ul>
                            <li>ItemNum: {{submenu1.ItemNum}}</li>
                            <li>ItemDesc: {{submenu1.ItemDesc}}</li>
                            <li>ActionCode: {{submenu1.ActionCode}}</li>
                            <li>ActionInst: {{submenu1.ActionInst}}</li>
                          </ul>
                      </li>
                </ul>
            </li>
            </ul>
        </li>
    </ul>

If you wish to easily handle the opening and closing of menus, consider integrating this code into an Angular accordion component for a more streamlined solution. Feel free to reach out if you need assistance with that implementation.

Answer №2

Are you attempting to create a nested list with children? Consider implementing a recursive pattern using ng-include to display all nested children. You can structure it like this:

<script type="text/ng-template" id="menuTree">
  {{ menuItem.name }}
  <ul ng-if="menuItem.children">
    <li ng-repeat="menuItem in menuItem.children" ng-include="'menuTree'"></li>
  </ul>
</script>

<ul>
  <li ng-repeat="menuItem in menuItems" ng-include="'menuTree'"></li>
</ul> 

The data structure used here may differ slightly from yours, but the concept remains the same. Check out this demo for clarification: http://jsfiddle.net/mmmxh8kq/

EDIT:

If your data is similar to the provided JSON and does not require a recursive menu, you can simplify it like so:

<ul>
  <li ng-repeat="menus in menuList.Menu">
    {{ menus.MenuNum }}
    <ul>
      <li ng-repeat="menuItems in menus.MenuItems">
        {{ menuItems.ItemDesc }}
      </li>
    </ul>
  </li>
</ul>  

Check out this demo for a clearer view: http://jsfiddle.net/n4mo80od/

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

Efficiently incrementing values within a specific index range in a Python list without relying on NumPy for vectorization

If I have a list of int, like this: arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] And I want to add 10 to elements from index 5 to index 10 (inclusive) so that the new arr is: arr = [0, 1, 2, 3, 4, 15, 16, 17, 18, 19, 20, 11, 12, 13] What is a f ...

Exploring nested objects and arrays with Plunker - extracting their values

I have retrieved two arrays, each containing nested objects, from API endpoints. One array (preview) consists solely of numbers. For example: [{ obj1:[1, 2], obj2:[3, 4] }] To obtain strings associated with IDs, I made another call to a different en ...

analyzing strings by comparing their characters to another string

In a scenario where I have two strings; let's call them string a="a-b-c" and string b="a-b". I am looking to determine whether every letter in string b is present within string a. ...

Trouble arises when incorporating a new feature onto a map with OpenLayers and Vue.js

I'm currently working on integrating a custom control into my map using OpenLayers with Vue.js. The Explore.vue component is responsible for creating the "map" (olmap) with OL, and I bind it to the child component LeftSideBar2.vue. However, when att ...

Creating IPv6 Mask from IPv6 Prefix Using Javascript: A Step-by-Step Guide

Write a JavaScript/TypeScript function that can convert IPv6 prefixes (ranging from 0 to 128) into the corresponding mask format (using the ffff:ffff style). Here are some examples: 33 => 'ffff:ffff:8000:0000:0000:0000:0000:0000' 128 => ...

Is it possible for a user to change the data stored in sessionStorage variables?

Incorporating client-side JavaScript into my project to save certain variables using Web Storage - specifically, the sessionStorage. However, uncertainty exists regarding whether a user holds the capability to alter these variable values. If this is indee ...

Using Angular ng-model with Bootstrap Modal is problematic when attempting to use it multiple times

Imagine you have a table with 10 lists of operators, each with an edit button. When you click on the edit button for operator 1, the modal pops up and displays the operator data in the input field as expected. However, when you close the modal and try to e ...

Transform a string into an object using AngularJS $parse function

Imagine having a server that sends back a response in the form of: { multiply:function(x,y) { return x*y; }, divide:function(x,y) { return x/y; } } Can this be converted into a functional method? I attempted to convert ...

What could be the reason that angularjs html template requests aren't appearing in the top websites when viewed in a

After referring to the link , I discovered a way to determine which programming tools different sites use for application development. However, when I debug HTTP requests using Firebug, I noticed that HTML requests are not explicitly shown in the log. Alt ...

What is the best way to send a multidimensional char array as a parameter in a C function?

I'm facing an issue with my code - it's not working properly. When I pass a char array like grid[r][c], I get the following errors: [Error] use of parameter 'r' outside function body [Error] use of parameter 'c' outside func ...

Streamline your processes by automating jQuery AJAX forms

I am looking to automate a click function using the code snippet below in order to directly submit form votes. Is there a method to develop a standalone script that can submit the votes without requiring a webpage refresh: <input type="submit" id="edit ...

Using Vue Composition API to invoke a child component's method that employs a render function

While using Vue composition-api with Vue2, I encountered an issue when attempting to call a method of a component with a render function from its parent component. Everything works fine without the render function. TemplateComponent.vue <template> ...

Tips for keeping the app on the same route or page even after a refresh

I'm currently diving into the world of React and am in the process of constructing a CRUD application. I've successfully created multiple pages that utilize react-router-dom for navigation with authentication. The pages are accessible only to log ...

Failed attempt in sending JSON array through AJAX to PHP process

My goal is to use an ajax call to send a JSON array to a PHP web service. Despite trying several solutions recommended for similar questions, I have not been successful. Here is the structure of my JSON array: var res= [{"id":-9007199254740990, "NW":{"x" ...

Several conditional statements in JSX

In my JSX Return() code, I am encountering an "If" issue when one of my conditions has 2 different 'onClick' events. There are 2 'a' tags, where one will display button 'X' if a statement is true and the other will display but ...

Preventing the form from being enabled by default when using 'ng-model'

I have an input field labeled name. I have set a default value of 'Enter your Name' using the ng-model, but this causes the form submit button to become enabled. How can I prevent the submit button from being enabled by the default value? Here i ...

A function with a specific name for sorting a multidimensional object based on a specified sub-key's value, without anonymity

My data consists of a collection of objects, not an array: var people = {}; people['Zanny'] = {date: 447, last: 'Smith'}; people['Nancy'] = {date: 947, last: 'William'}; people['Jen'] = {date: 147, last: &a ...

Aurelia: Understanding the Integration of a View/ViewModel from an npm Package

We've decided to implement Aurelia for the frontend of our application. With multiple projects in the pipeline, we are looking to streamline the process by packaging our custom code into npm packages that can be easily integrated by developers. This w ...

Deselect a checkbox by selecting a radio button with just Javascript code

Hey there! I'm currently delving into the world of pure JavaScript and could really use some guidance on a particular issue. Here's what I'm aiming to accomplish: I'd like to design a checkbox that triggers the opening of a window whe ...

Is there a more efficient method for creating HTML with coffeescript / jQuery besides using strings?

Today marks my first attempt at creating a "answer your own question" post, so I hope I am on the right track. The burning question in my mind was, "Is there a more efficient way to generate HTML with jQuery rather than using tag strings?" My goal is to c ...