Angular JS merges various records under a common category from a JSON document

[{"Category":"cat","Value":"large cat"},
{"Category":"cat","Value":"small cat"},
{"Category":"dog","Value":"large dog"},
{"Category":"dog","Value":"little dog"},
{"Category":"dog","Value":"cute dog"}]

If I have a JSON file structured like this, how can I utilize AngularJS to display the data based on categories as shown below?

cat 
large cat
small cat
dog
large dog
little dog
cute dog

I have tried searching for solutions online, but most of them focus on removing duplicate entries rather than grouping items under the same category.

I experimented with using ng-repeat along with a custom filter algorithm from this tutorial.

Can anyone guide me on how to achieve the desired outcome?

Below is the code snippet that I am currently utilizing:

<div ng-repeat="animal in animals | unique : 'Category'">
        <div>{{animal.Category}}</div>
        <div>{{animal.Value}}</div> 
</div>

However, the current implementation produces the following result:

cat
large cat
dog
large dog

Unfortunately, this output does not align with my expectations.

Answer №1

Check out this functional example

To identify unique categories, utilize the custom filter loop you've created. Then, implement a nested loop to display animals corresponding to each category as shown below:

<div ng-repeat="category in animals | unique : 'Category'">
  <span style="font-weight: bold">{{category.Category}}</span>
  <div ng-repeat="animal in animals" ng-show="animal.Category === category.Category">
    {{animal.Value}}
  </div>
</div>

Answer №2

For achieving the desired result, you can utilize Array#reduce and Array#map.

let values = [{
    category: "cat",
    value: "large cat"
}, {
    category: "cat",
    value: "small cat"
}, {
    category: "dog",
    value: "large dog"
}, {
    category: "dog",
    value: "small dog"
}, {
    category: "dog",
    value: "cute dog"
}, {
    category: "turtle",
    value: "water turtle"
}, {
    category: "turtle",
    value: "land turtle"
}];

let groupedData = values.reduce((output, item) => {
    output[item.category] = output[item.category] || [];
    output[item.category].push(item.value);

    return output;
}, {});

console.log(groupedData);

let categoriesData = Object.keys(groupedData).map(key => ({key, values: groupedData[key]}));

console.log(categoriesData);

Answer №3

Utilize the groupby filter to categorize animals

<div ng-repeat="animal in animals  |  groupBy:'Category'" >
<h2 ng-show="animals[$index - 1].Category != animal.Category">{{item.Category }}</h2>
<ul>
    <li>{{animal.Value}}</li>
</ul>

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

Unable to include a controller in AngularJS that is declared in a different file

I am new to using Angular. Currently, all of my controllers are defined in the controllers.js file following these patterns: function A($scope){.....} function B($scope){.....} function MainCtrl($http) {.....} . . . angular .module('myApp') ...

Handling dynamic routes with React Router 4 and the 404 path

I have been working with the latest version of React Router (4) and have implemented a dynamic route configuration as described in the tutorial. The routes are functioning correctly, except for when I tried to add a 404 path following the tutorial's i ...

What is the process for transforming promises into async await syntax?

login() { return new Promise((resolve, reject) => { userCollection.findOne({email: this.data.email}).then((myUser)=>{ if (myUser && myUser.password == this.data.password) { resolve("Congrats! Succe ...

A guide on activating dropdown buttons individually using AngularJS (Cascading dropdowns)

When it comes to cascading dropdowns (for example: with 3 dropdowns), the challenge is to disable the 2nd and 3rd dropdown initially. Only when a user selects an option in the 1st dropdown, should the 2nd dropdown be enabled. Similarly, once an option is s ...

Interactive Vue tree view featuring draggable nodes

I am currently working on creating a tree component in Vue.js, and I am facing challenges with implementing drag and drop functionality in the Tree component. I am unsure where to begin, as I have looked through similar code on GitHub but I am struggling t ...

Replicating form fields using jQuery

I have come across many questions similar to mine, but unfortunately none of them address the specific details I am looking for. On a single page, I have multiple forms all structured in the same way: <form> <div class="form-group"> ...

An unexpected identifier error occurred following an Ajax request

Below is the HTML code that I am working with: <div id="texttheory" class="centertext">'. $short .' </div>'; <button id="thbutton" class="theory_button" onclick="javascript:changetheory('.$long.')"> <im ...

Can anyone offer a straightforward method for obtaining JavaScript output in Java within the Eclipse environment?

Currently, I am attempting to retrieve the return value from a JavaScript function that I have created. Although I can achieve this using a complex method involving listeners, I am interested in utilizing Eclipse's Browser.evaluate method. For practi ...

Is there a way to ensure that a "catch all other" route in the Vue Router will also capture the URL if a portion of it matches a predefined route?

After following the suggestion to implement a catch all route from this article, I realized that it does not capture URLs that partially match a defined route. routes: [ { path: "/album/:album", name: "album", component: Album, } ...

Zod offers the flexibility to customize validation for optional keys

Currently, I am exploring the utility of using zod within my application. I am facing a minor issue when attempting to parse an object that may contain optional keys. While using .passthrough allows the keys to remain in the object, I am interested in cu ...

Implementing Dynamic Weight-based Pricing with CodeIgniter and AJAX

My shopping cart website utilizes ajax and Codeigniter to add products without reloading the page. Originally, I displayed a single net weight for each product. However, I recently switched to multiple net weights for the same product. Unfortunately, I am ...

Javascript Google Maps API is not working properly when trying to load the Gmap via a Json

Trying to display a map using Gmaps and Jquery Ajax through JSON, but encountering difficulty in getting the map to appear on the page. The correct coordinates are being retrieved as confirmed by testing in the console. Puzzled by why it's not showin ...

Exploring the streamlined process of verifying a user's ability to connect using Slim in a RESTful

I have a unique situation where my SLim API is integrated into my ANgularJS application to interact with the database like so (for instance): Sample controller code: $scope.testDatabaseItems = function(){ $http.get(pathApi + 'items').succes ...

Removing an object in Three.js using scene.getObjectByName() method

When developing my game, I encountered a challenge. I'm loading 4 different buildings and creating 15 clones of each within a for loop. These clones are then added to an array called masterBuildingArray, which I iterate through using a forEach loop. T ...

Display nested array objects of varying levels within VUE

How do I display nested elements on the UI when dynamically generated based on a parent element's selected option (e.g. List)? For example, in the code below, when creating a field and selecting the List option, another nested should appear, and so o ...

Failed PHP response when jQuery was called

I'm working on a project that involves two files: one PHP and one HTML. The HTML file acts as the user interface where users input their queries, while the PHP file handles the processing and events before returning the output back to the HTML file. I ...

Socket.io: sending signals without receiving any responses

I've been working on a real-time socket.io project that involves a collaborative whiteboard app. I'm facing some issues with emitting data. server.js const express = require('express') const app = express(); const http = require(&apos ...

Bootstrap modal fails to appear on screen

Using PHP, I generate a link from the controller. The link is stored in $retailer["url"] as 0125myimage.jpg <a onClick="crop('.$retailer["url"].')" data-target="#styledModal3" href="#" class="fa fa-edit lupa"></a> Here is my JavaSc ...

Only load the value in ref when it is specifically requested in Vue

Within my Vue project, I am utilizing a ref variable that stores data retrieved from a database. This reference is contained within Pinia's setup store for easy access. The objective is to load the data only when requested by the user and then always ...

Update and send back variable on the spot

I'm interested in learning the syntax for creating an inline function that can accept a parameter, perform a simple modification on it, and return it all in a single line. Here's an example: (input) => { input.status = 'complete'; ...