Dealing with duplicate keys in an object while using AngularJS ng-repeat

My goal is to utilize the ng-repeat function to display the remaining data if the attribute is the same. To clarify, here is an example:

Consider a JSON sample, which consists of an array of books:

[{"Genre":"Sci-fic","Name":"Bookname1"},
 {"Genre":"Sci-fic","Name":"Bookname2"},
 {"Genre":"Non sci-fic","Name":"Bookname3"},    
 {"Genre":"Non sci-fic","Name":"Bookname4"}]  

If books belong in the same genre, I want the genre type to serve as the heading of the accordion and list the attributes for those books without repeating the heading. The issue I'm facing is that since the json array of objects comes from a data model, I can't filter the type without replicating the genre entry.

The structure I currently have involves setting the Book.Genre as the accordion heading, with each accordion-group containing a list of all books belonging to that genre.

For more information, you can visit: http://plnkr.co/edit/PwIrOAIT3RRaE2ijzGZb?p=preview

Answer №1

I've yet to find a solution for this issue... One way that might work is by removing the duplicates before including that model in your scope...

Take a look at this jsFiddle example...

http://jsfiddle.net/mcpDESIGNS/Uz5tM/1/

var books = [
             {"Genre":"Sci-fic", "Name":"Bookname1"},
             {"Genre":"Sci-fic", "Name":"Bookname2"},
             {"Genre":"Non sci-fic", "Name":"Bookname3"},    
             {"Genre":"Non sci-fic", "Name":"Bookname4"}
               ];

var unique = [],
    blocked = [];

unique.push(books[0]);
blocked.push(books[0].Genre);

for (var i = 1; i < books.length; i++) {
    if (blocked.indexOf(books[i].Genre) <= -1) {
        unique.push(books[i]);
        blocked.push(books[i].Genre);
    }
}

$scope.Books = books; 
// [{Genre: "Sci-fic", Name: "Bookname1"}, 
//  { Genre: "Non sci-fic", Name: "Bookname3" }];

Answer №2

the issue arises from having duplicate values in the "generes" array when using track by $index

  <div ng-repeat="genere in generes track by $index"></div>

if you wish to group your model by Genre, you can utilize underscore.js. Check out this example for reference.

View :

<div ng-app="app">

    <div ng-controller="ParentCtrl">

    <ul class="about-tab-titles" close-others="oneAtATime">
            <li  ng-repeat="(key ,book) in model">
                {{key}}

                <ul>
                    <li ng-repeat="b in book ">{{b.Name}}</li>
                </ul>
            </li>
        </ul> 
    </div>
</div>

JS:

angular.module('app', [])

function ParentCtrl($scope) {
    var books = [{
        "Genre": "Sci-fic",
            "Name": "Bookname1"
    }, {
        "Genre": "Sci-fic",
            "Name": "Bookname2"
    }, {
        "Genre": "Non sci-fic",
            "Name": "Bookname3"
    }, {
        "Genre": "Non sci-fic",
            "Name": "Bookname4"
    }];

    $scope.model = _.groupBy(books, 'Genre');

}

Answer №3

After much trial and error, I finally discovered a solution that perfectly fits my needs. This guide on applying AngularJs filters within nested ng-repeats was instrumental in my success. While I did make some modifications to suit my specific data structure, the core concept remained unchanged.

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

What could be the reason for the sudden failure of my jQuery + AJAX functionality?

As a novice in JavaScript/jQuery/AJAX, I have a suspicion that the issue lies in some typo that I may have overlooked. Everything was working perfectly, but when I made some edits, the hide() + show() methods stopped functioning (I tested it on both Firefo ...

Learn how to create a smooth and consistent horizontal image slider using JavaScript to manipulate transition transforms

Does anyone know how to create a seamless sliding effect for a series of images in Vuejs? Let's say we have images 1, 2, 3, 4, and 5 When the first slide occurs, the order of images should be: 2, 3, 4, 5, 1 For the second slide: 3, 4, 5, 1, 2 And ...

Don't forget to set up your reminder notifications for Apple iOS devices with simple php

Here are the four notification settings available: 1. Renew Tax 2. Renew Health Insurance 3. Renew Car Insurance 4. Renew Residential Insurance If a user decides to turn off any of these settings on their mobile phone, NO notifications will be sent. How ...

Is incorporating RequireJS into an AngularJS project a valuable decision?

Is it true that AngularJS has its own module loading mechanism built-in and using RequireJS is unnecessary or even inefficient? I am working on an Angular project where the index.html file is becoming quite large. Would incorporating RequireJS help reduc ...

Error: Attempting to subscribe to a post request returned a null result

Every time I attempt to subscribe to a post request, the TypeError: result is null is returned My setup involves an Angular CLI connecting with a Spring Boot application for a simple login page. My goal is to save the response header in local storage. Be ...

The onClick function is called when I fail to click the button within a React form

I set up a form and I would like to have 2 ways to submit it: One by filling out the input field and pressing enter One by recording voice (using the react-speech-recognition library) However, after adding the second way, the input fi ...

Exploring the Power of Pythons, Selenium, and XPATH for Handling New Windows

Is it possible to retrieve an element through XPath after using the .click() method when that element is located within a section of JavaScript known as BODY_BLOCK_JQUERY_REFLOW and appears only after the click action? I am attempting to access this speci ...

Display an image in response to a button click using JavaScript

I am currently working on a feature that will display information when a radio button is pressed. I also want to include an image, but I am facing an issue where the text displays correctly but the image does not appear. What steps should I take to resolve ...

How can I implement a promise loop in Angular that continues until it encounters a rejection?

My goal is to efficiently load around 10000 resources, but loading them all at once during the resolve phase is taking too long due to some calculations. I then had the idea to load the resources page by page sequentially, however, since all resources need ...

Display or Hide certain Items/Elements depending on the chosen Category

I have multiple images within a div, each image belonging to a specific category. I want to display only the images from a selected category and hide all others. Initially, all images are in the category all. When selecting the category blue, for example, ...

Show the Canvas element at the back of the DIV

This particular question requires a clear explanation. My goal is to have the canvas act as a background element on the page, while the main content of the page starts in its usual position. I attempted using separate DIVs with their own Z-index values, bu ...

What is the best way to search for a specific string within an Airtable record that may also have additional data included?

By utilizing the filterByFormula method in the airtable api, I am able to query and choose records that include a specific item (string). However, this query will only return the records that exclusively have that particular string. Referencing the airtab ...

Reorganizing Arrays in Javascript: A How-To Guide

I have an array in JavaScript called var rows. [ { email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="81f4f2e4f3b0c1e4f9e0ecf1ede4afe2eeec">[email protected]</a>' }, { email: '<a hre ...

How can I reset the search input in v-autocomplete (multiple) after selecting a checkbox from the drop-down menu?

I am facing an issue with the v-autocomplete component from Vuetify. Currently, when I enter "Cali" in the search input and select "California" from the dropdown list, the "Cali" value remains in the search input field. I need the entered value to be clear ...

Guide to Rolling a Set of 5 Dice

I am looking to develop a game involving 5 dice. I have already created a function to roll one die using a random method, but I am unsure how to extend this functionality to the remaining four dice without having to create a separate method for each one. ...

When the mouse is clicked down, make elements move along with the cursor

Is there a way to make picture elements follow the mouse cursor only while the mouse is pressed down? The current script works well but starts following the cursor only after it has been released, which is not the intended behavior. I tried placing the in ...

Determine the overall cost based on varying percentage increases for each step

I am currently working on developing a price estimation calculator. Here is the breakdown: For 1000 MTU, the price will be 0.035, resulting in a total of 35. For 2000 MTU, the price will be 0.034, making the total 67. For 3000 MTU, the price will be 0.03 ...

Incorporating JSON data into an HTML table

Looking to populate an HTML table with JSON data, but struggling with parsing and appending the data correctly. Can anyone provide guidance or assistance? <!DOCTYPE html> <html> <head> <title>JSON Demo</title> < ...

Steps for implementing scroll-based pagination in a select dropdown

HTML <select class="form-control choice requiredField" id-available name="SelectData" ng-model="box.box_id" title="Select"> <option value="" disabled selected>{{'_SELECT_BEACON_' | i18n}}</option> <option value="{{y. ...

Avoiding repetitive clicking of buttons in jQuery—strategies for success

Hello, I am currently facing an issue where I need to reset the content of a div using an AJAX call when a user clicks a button. However, if the user clicks multiple times in quick succession, an error occurs. I would like to find a way to prevent users fr ...