Angular's multidimensional array functionality allows for complex data structures to be

Is it possible to programmatically loop through a multidimensional array obtained from an API?

{
    success: true,
    categories: [{
            cat_id: "2",
            name: "This is category One",
            description: null,
            photo_url: "/img/test.png",
            order: "1",
            items: [{
                    item_id: "1",
                    title: "Desk",
                    item_url: "/690928460",
                    photo_url: "/desk.png",
                }, {
                    item_id: "2",
                    title: "Chair",
                    item_url: "/18882823",
                    photo_url: "/chair.png",
                },
            }]
    }]
}

The controller code snippet:

myApp.controller('items', function($scope, $http, $location, Data) {
    var apiUrl = '/api/items';
    $http.get(apiUrl).
    success(function(data) {
        $scope.data = Data;
        $scope.allData = data;
    });
    $scope.changeView = function(view) {
        $location.path(view);
    }
});

In the Angular index file:

<div ng-view=""></div>

View file structure:

<div class="scrollable categories-container animated-fast slideInUp">
    <div class="container categories">
        <div class="row" ng-repeat="categories in allData">
            <div class="col-xs-6" ng-repeat="category in categories">
                <div class="items">
                    <div class="title">
                        {{ category.name }}
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

While looping through category names works fine, I am struggling to comprehend how to efficiently return items for each individual category.

Answer №1

If you're looking to handle data using nested for loops, I recommend looping through categories and items separately to manage complexity effectively.

Here's a simple approach within your success function:

var items = [], categories = []
for(var i = 0; i < data.categories.length;i++){
    categories.push(data.categories[i].name);
    for(var j = 0; j < data.categories[i].items.length;j++){
        items.push(data.categories[i].items[j].name);
    }
}
console.log(categories);
console.log(items);

UPDATE:

I see now that you have included HTML code as well. Here is my updated solution:

<div class="scrollable categories-container animated-fast slideInUp">
    <div class="container categories">
        <div class="col-xs-6" ng-repeat="category in allData.categories">
            <div class="items">
                <div class="title">
                    {{ category.name }}
                </div>
            </div>
        </div>
    </div>
</div>

UPDATE 2:

In response to your question: To display the items based on selected category, you can use ng-click attribute. While a directive could be an option, it's not essential:

<div class="scrollable categories-container animated-fast slideInUp">
    <div class="container categories">
        <div class="col-xs-6" ng-repeat="category in allData.categories">
            <div class="title" ng_click="selected_category = category">
                {{ category.name }}
            </div>
        </div>

        <div class="col-xs-6" ng-repeat="item in selected_category.items">
            <div class="title">
                {{ item.name }}
            </div>
        </div>
    </div>
</div>

Once the categories data is loaded, the first ng-repeat will populate the categories section. Clicking on a category will update the selected_category object, which in turn updates the view with corresponding items using Angular's two-way binding.

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

Can someone provide guidance on iterating through a nested array in d3 and appending child elements accordingly?

Looking at my JSON data, here is an example of what it contains. var data = [ { animal: 'dog', names: [ 'mark', 'cooper', 'pooch' ] }, { animal: 'cat', names: [ 'mary', 'kitty' ] ]; ...

At the moment of execution, the imported npm package module is not defined

Recently, I added a package named "js-linq" (available at https://github.com/battousai999/js-linq) using the command npm install js-linq and it seemed to install successfully. This process is clearly outlined in the npm documentation at https://www.npmjs.c ...

Issue with THREE.CubeTextureLoader where edges appear 1px too small

My latest project involved creating a panorama cube using THREE.CubeTextureLoader: pano = [ 'scenes/4/2048/px.jpg', 'scenes/4/2048/nx.jpg', 'scenes/4/2048/py.jpg', 'scenes/4/2048/ny.jpg', 'scenes/4/ ...

Issue encountered when passing an argument to a map callback function within a React component

I am encountering an error in my React component while using a map function to display data. The issue arises when passing a callback function and trying to access the classes property, resulting in the error message Uncaught ReferenceError: classes is no ...

What is the proper way to invoke a function in the code-behind using JavaScript?

I need to invoke a function in the code behind from JavaScript Button : <button class = "btn btn-outline btn-danger dim" type = "button" onclick = "confirmDelete ()"> <i class = "fa fa-trash"> </i> ...

What is the method for combining two box geometries together?

I am looking to connect two Box Geometries together (shown in the image below) so that they can be dragged and rotated as one object. The code provided is for a drag-rotatable boxgeometry (var geometry1). What additional code do I need to include to join t ...

Pointer to a pointer to an array of integers compared to an array of pointers to pointers to integers

Consider the scenario where 3 integers, labeled as A, B, and C, are transformed into pointers and grouped in an array called arrayABC: int A = 1; int B = 2; int C = 3; int *ptA = &A; int *ptB = &B; int *ptC = &C; int **arrayABC[] = { &ptA ...

The courier stranded in the process of sending a request - express js mongodb

Help needed with postman request issue when condition is not met var express = require('express'); var app = express(); var bodyParser = require('body-parser'); var multer = require('multer'); var upload = ...

Set up a JavaScript ArrayBuffer containing only zeros

Looking for an efficient way to quickly set all indices in an ArrayBuffer to 0. I am aware of manually iterating through it, but I want a faster built-in method since I need to perform this task once per animation frame. ...

Monitoring and recording the current line number during evaluation

Recently, I've been experimenting with eval to modify a $scope object named variables. This is the watcher I'm using: $scope.$watch(function () { return $scope.variables; }, function (variables) { console.log('changed!'); }, true) ...

SMTPConnection._formatError experienced a connection timeout in Nodemailer

Our email server configuration using Nodemailer SMTP settings looked like this: host: example.host port: 25 pool: true maxConnections: 2 authMethod: 'PLAIN' auth: user: 'username' pass: 'pass' We encou ...

What is the best way to decode a Json String using angularJS?

Exploring a nodeJSON string: { "Name": "Addition", "Id": "3", "ParentId": "1", "children": [ { "Name": "Two Numbers", "Id": "5", "ParentId": "3", "children": [] }, { "Name": "Three Numbers", "Id": "6 ...

Secret button that remains unresponsive upon initial click after materializing

I am facing a problem with my two buttons in the HTML code. One button is supposed to plot data, while the other is meant to download data. The issue arises when the plot button has data and the Excel download button should become visible. Although this fu ...

Disable the default marker in Mapbox Geocoder

As a newcomer in the world of ReactJS and Mapbox GL JS, I am working on a project where I have successfully integrated a map with Geocoder, Navigation Controls, and Markers based on locations from a JSON file. However, I encountered an issue - whenever I s ...

Removing the gap between the clicked point and the draw point in Html5 canvas

To better understand my issue, please refer to the image linked below: In the image, you can see that when I scroll down and click on the canvas to point a position, it creates space between the clicked point and where the line is drawn. Below is the cod ...

How can one smoothly rewind X frames in a video or animation on a webpage without experiencing lag?

For my thesis presentation, I decided to make it available online as a video with custom controls resembling a powerpoint slideshow. The challenge I encountered was with transitions between slides in an animated video. Certain transitions needed to loop fo ...

Looking for assistance with aligning the content of an input label using Bootstrap?

Is there a way to adjust the label content if it is larger than the input box size? My goal is to keep all input boxes on the same line while allowing labels to wrap accordingly. https://i.sstatic.net/NrLck.png I'm trying to achieve the alignment sh ...

What is the process for logging out when a different user signs in using Firebase authentication in a React Native application?

I am new to React Native and facing challenges with managing authentication state in my application. Currently, I am using Redux but have not yet implemented persistence for user login. I have incorporated Firebase authentication. Essentially, I would li ...

Refreshing this Div using data retrieved from an ajax call

I am encountering an issue with multiple forms on my website. Each form accepts a file upload and then displays the upload status in a specific element. However, when updating one form, the status is displayed on a different form, causing confusion for use ...

What is causing the image to not be centered in the canvas when using AngularJS?

Can you please help me troubleshoot why my image is not centered using the method below? function drawImage() { clear(); element.save(); element.scale(currentScale, currentScale); ...