Avoiding the addition of duplicate records when using a for each loop in Angular

I have a directive code that dynamically forms JSON. The challenge is to create a JSON without duplicate object names.

Angular Code:

bosAppModule.directive('layoutTableCellControlLabelRender',function($compile,$rootScope){
    var layoutTableCellControlLabelObj={};

    var soJSON = {
            entityInfo: {
                entity: "",
                tenantId: "",
                timeStamp: new Date().toJSON().toString()
            },
            collections: {

            }
    };
    var myobj={};
    linkFnTableCellControlLabel=function(scope, element, attributes, controllerCtrl) {
        scope.labelData="NO DATA";

        angular.forEach(scope.pageObject.collections.objectattribute.rowset, function (value, index) {
            if(value.objectattributeid==scope.attributeId){
                scope.labelData=value.objectattributelabelname;
                scope.attributeName=value.objectattributename;
                
                angular.forEach(scope.pageObject.collections.object.rowset, function (value2, index2) {
                    if(value2.tenantobjectid==value.objectattributeobjectid){
                        scope.objectname=value2.tenantobjectname;
                        if(!soJSON.collections[scope.objectname]) {
                            soJSON.collections[scope.objectname]={
                            "meta": {
                                "parentreference": "***",
                                "pkname": "***",
                                "fkname": "***"
                              },
                              "rowset": [],
                              "rowfilter": []
                             };
                        }

                    }
                });

                myobj[scope.attributeName]="test";
                soJSON.collections[scope.objectname].rowset.push(myobj);
            }
        });

        console.log(JSON.stringify(soJSON));

    };


    layoutTableCellControlLabelObj.scope={attributeId:'=',layoutData:'=',pageObject:'='};
    layoutTableCellControlLabelObj.restrict='AE';
    layoutTableCellControlLabelObj.replace='true';
    layoutTableCellControlLabelObj.template="<div class='col-xs-12 col-sm-12 col-md-6 col-lg-6' attribute-name={{attributeName}} attribute-id='tablecellcontrol.layouttablecellcontrolbindingobjectattributeid' " +
                                            "layout-data='layoutData' page-object='pageObject'><label class='k-label pull-right'>{{labelData}}</label></div>";

    layoutTableCellControlLabelObj.link = linkFnTableCellControlLabel;

    return layoutTableCellControlLabelObj;  
});

The JSON created by the above code contains duplicated records in the rowset due to looping. I need assistance in preventing this duplication and ensuring each record is only created once. If you require further information on this matter, please let me know.

JSON

 {
  "entityInfo": {
    "entity": "",
    "tenantId": "",
    "timeStamp": "2016-04-07T07:25:49.711Z"
  },
  "collections": {
    "Customer29Jan16": {
      "meta": {
        "parentreference": "***",
        "pkname": "***",
        "fkname": "***"
      },
      "rowset": [
        {
          "CuId": "test",
          "Name": "test",
          "Quantity": "test",
          "Rate": "test",
          "Amount": "test"
        },
        {
          "CuId": "test",
          "Name": "test",
          "Quantity": "test",
          "Rate": "test",
          "Amount": "test"
        },
        {
          "CuId": "test",
          "Name": "test",
          "Quantity": "test",
          "Rate": "test",
          "Amount": "test"
        },
        {
          "CuId": "test",
          "Name": "test",
          "Quantity": "test",
          "Rate": "test",
          "Amount": "test"
        },
        {
          "CuId": "test",
          "Name": "test",
          "Quantity": "test",
          "Rate": "test",
          "Amount": "test"
        }
      ],
      "rowfilter": []
    }
  }
}

Answer №1

It may not always be the same json structure, but one possible solution is to utilize uniqby method from lodash on your rowset array.

_.uniqBy(json.collections.Customer29Jan16.rowset, function (e) {
   return e.CuId;
});

Live Demo

UPDATE

If you have multiple customers, you can iterate over a customer array:

arrayOfCustomers = (Object.keys(json.collections));

for(var i = 0 ; i < arrayOfCustomers.length; i++){
  json.collections[arrayOfCustomers[i]].rowset  = _.uniqBy(json.collections[arrayOfCustomers[i]].rowset, function (e) {
    return e.CuId;
  });
}

Updated Live Demo

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

Issue with Angular2: The [routerLinkActive] directive does not update when using _router.navigate

My app includes several routerLinks that I have styled using [routerLinkActive]="['active']". Everything works perfectly when I click on one of the routerLinks to navigate. However, when I try to navigate using: this._router.navigate( [ thisUrl ...

Using Highcharts to create a line graph and populating the xAxis with data retrieved

I want to create a line graph using Highcharts with data in the following JSON format: [{"Monat":"April","d07geb":1.5},{"Monat":"June","d07geb":0.5},{"Monat":"March","d07geb":0.5},{"Monat":"May","d07geb":0.2}] The "Monat" field represents the month, whic ...

In what way does JavaScript determine the timing for executing a function that is passed by reference implicitly? Illustrate with a

Within my React example application, I have assigned the function "manipulateUsername" as an event listener to a child component by passing it as a reference. Here is the code snippet from App.js: import React, { Component } from 'react'; impor ...

Conflict in Vue.js between using the v-html directive and a function

Below is the component template for a notification: <template> <div> <li class="g-line-height-1_2"> <router-link :to="linkFromNotification(item)" @click.native="readNotification(item)" v-html="item. ...

"Encountering a Unicode malfunction in a string that has already been

Currently facing an issue with concatenating a string after decoding it earlier in my code: import json import requests import jsonobject for i in range(0, 3): if i == 0: var = "0" var2 = "Home" elif i == 1: var = "1" ...

Validation for Hebrew characters using ng-pattern

Looking to implement ng-pattern for validating a text input field that should only accept Hebrew characters. The issue is that sometimes the input is accepted and other times it is rejected for unknown reasons, such as accepting the first letter but not th ...

Create a feature where radios within one controller can toggle the visibility of an element in a separate controller

I am currently working on establishing a connection between different controllers to control the visibility of a div based on radio button selection in another controller. With some assistance, I have made progress in getting this functionality partially ...

Retrieve the element by its Id for precise targeting on a particular webpage

I'm new here and looking for some assistance, so please help if you can :) I'm working on a web page but encountered an issue that I hope you can help me solve. Here are the 3 files involved: home.html --> Main page login.html --> Page ...

Use CSS to position the SVG element to the bottom right corner of the screen

I have a <div> on the page with the CSS class .svgImage applied to it. Whenever I resize the browser window, the svg image resizes correctly but keeps shifting its position on the page. When I make the browser window vertically smaller, the svg imag ...

What is the best way to display nested JSON images in SwiftUI without disrupting the existing Swift theme?

I am currently working on displaying the book cover image next to the disclosure view containing information about the book. The images are being retrieved from a struct and displayed in a disclosure group along with nested JSON data. These JSON files are ...

"An error occurred while trying to retrieve memory usage information in Node.js: EN

Is there a way to successfully run the following command in test.js? console.log(process.memoryUsage()) When running node test.js on my localhost, everything runs smoothly. However, when attempting to do the same on my server, I encounter this error: ...

Angular: Retrieving the Time Format from the Browser

Is there a way to retrieve the time format from the operating system or browser within Angular in order to display time in the user's preferred format? I have attempted to search for a solution, but have come up empty-handed. Thank you in advance! ...

What is the best way to retrieve the value of a nested function in JavaScript?

I am currently working on a project that involves a function. function findParentID(parentName) { Category.findOne({ categoryName: parentName }, function (err, foundParent) { var parentID = foundParent.categoryID;    return parentID;<br> } ...

How can I implement a redirect back to the previous query page post-authentication in Next.js 13?

To enhance security, whenever a user tries to access a protected route, I plan to automatically redirect them to the login page. Once they successfully log in, they will be redirected back to the original protected route they were trying to access. When w ...

Swapping out a background video for a background image in cases where auto-play is restricted on the device

How can I replace an auto-play background image with a static image on devices that do not support auto-play? The <video> tag's POSTER attribute works, but it seems that on my iPhone (which does not allow auto-play), the video is still downloade ...

Has anyone had experience integrating iScroll with AngularJS?

Just starting out... I'm currently working on developing an app using AngularJS and I'm looking to add iScroll features. Has anyone successfully integrated iScroll with AngularJS before? If you have, would you mind sharing some tips or advice? ...

Help! I can't seem to figure out how to detect offline status in JavaScript

I am a beginner at JavaScript and I am currently working on implementing an example from the W3C website into my WebApp that will be running within the PhoneGap framework... Although it seems like a simple task, I am facing an issue where the event listen ...

Utilizing the map() method for iterating through a nested property within a React component

Currently, my React setup involves rendering a prop named area which has the following structure: [{ "id": 1, "name": "Europe", "Countries": [{ "id": 1, "name": "Iceland", "Cities": [{ "id": 1, " ...

Looking for assistance with parsing C# / .NET 6 into individual objects

I am currently working with the JsonSerializer.Deserialize() method from the System.Text.JSON library in .NET 6. The JSON format is beyond my control. While I have successfully used this method before, the data I'm dealing with now is slightly more ...

Troubleshooting a pair of .factory errors in AngularJS and Ionic

I am facing an issue with two .factory functions, where the second one throws an error. It seems like there is a restriction on having multiple .factory functions. Any assistance would be greatly appreciated. Thank you .factory('RawData', func ...