Verify the existence of the object before adding it to the array

Looking to iterate through a JSON response in order to verify the existence of a key/value pair, and if not present, include it in the array.

  $scope.InitProdToArray = function (data) {
    angular.forEach($scope.data.obj.Product, function(value, index) {

        if (value.Product_type != 'T' ) {
            $scope.data.obj.Product.push({Product_type: 'T'});
        }
        if (value.Product_type != '16364NB' ) {
            $scope.data.obj.Product.push({Product_type: '16364NB'});
        }
        if (value.Product_type != '39087NB' ) {
            $scope.data.obj.Product.push({Product_type: '39087NB'});
        }
        if (value.Product_type != 'C' ) {
            $scope.data.obj.Product.push({Product_type: 'C'});
        }
        if (value.Product_type != '4NB' ) {
            $scope.data.obj.Product.push({Product_type: '4NB'});
        }        
    });

  JSON: $scope.data.obj.Product = 
                    [{
                        "Count": 28,
                        "Product_type": "T"
                    }, {
                        "Count": 88,
                        "Product_type": "4NB"
                    }, {
                        "Count": 20,
                        "Product_type": "C"
                    }, {
                        "Count": 3,
                        "Product_type": "39087NB"
                    }
                ]

This method is currently ineffective as I am duplicating product_type values in the resultant JSON by pushing the key/value pairs for each iteration. Is there a way to prevent duplicate entries from being added?

Answer №1

It appears as though your type check may be flipped around. Instead of using

if (value.Product_type != 'T' ) {...
, consider utilizing
if (value.Product_type == 'T' ) {...
. This way, you'll only add to the Product array when the type matches.

In addition to that, you can also verify before adding if the Product array already includes a key of that type:

if($scope.data.obj.Product.indexOf(value.Product_type)!==undefined)

Answer №2

It appears from your code that you are focusing on search and insert operations rather than dealing with key/value pairs.

If you are targeting modern browsers, there is a useful function called find that can be used for this purpose.

var productTypes = ['T', '16364NB', '39087NB', 'C', '4NB'];

angular.forEach(productTypes, function(value) {
    var exists = $scope.data.obj.Product.find(function(item) {
        return (item.Product_type == value);
    });

    if (!exists) {
        $scope.data.obj.Product.push({
            Product_type: value,
            count: 0
        });
    }
});

For older browser support, it's recommended to include a polyfill for the find function as well.

Answer №3

var CATEGORIES = { A: 'A', B1: '1B', X: 'X', Y2Z: '2YZ'};
var items = [{ "Count": 28, "Category_type": "A" }, { "Count": 88, "Category_type": "1B" }];

/* verifying if the element key is not set to a specific value....*/
function checkKeyInElement(keyToVerify, element) {
return element.Category_type === keyToVerify;
}

/* checking for the absence of elements in array with the specified key ...*/
function noElementsWithKeyinArray(keyToCheck, arr) {
return !!arr.filter(function (element) { return checkKeyInElement(keyToCheck, element); }).length;
}

/* an alternative method to confirm the absence of elements in array with the specified key ...*/
function noElementsWithKeyinArray2(keyToConfirm, arr) {
return arr.map(function (element) { return element.Category_type; }).indexOf(keyToConfirm) > -1;
}

function initItemsToArray(sourceArr) {
if (!noElementsWithKeyinArray(CATEGORIES.A, sourceArr)) { sourceArr.push({ Category_type: CATEGORIES.A }); }
if (!noElementsWithKeyinArray(CATEGORIES.B1, sourceArr)) { sourceArr.push({ Category_type: CATEGORIES.B1 }); }
if (!noElementsWithKeyinArray(CATEGORIES.X, sourceArr)) { sourceArr.push({ Category_type: CATEGORIES.X }); }
if (!noElementsWithKeyinArray(CATEGORIES.Y2Z, sourceArr)) { sourceArr.push({ Category_type: CATEGORIES.Y2Z }); }
}

initItemsToArray(items);
console.log(items);

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

Click on a div to smoothly scroll to the top, then automatically scroll to the bottom if already at the top position

I've implemented a JQuery code on my website that allows the page to scroll to the top when clicking on a div with the class of .bottom. The code is working perfectly fine, here it is: function scrollToTop(){ $('.bottom').click(function ...

Enhance with Laravel combined with AngularJS

I've encountered some issues with the "edit" part while working on a Laravel + AngularJS CRUD application. An internal server error is being displayed, and I'm seeking assistance to understand its cause. Error "GET localhost/crudtcc/public/ap ...

Guide to tallying the occurrences of a specific key within an object array and attaching the count to each key's current value

Is there a way to determine the number of occurrences of the 'value' key within an object that is part of an array, and then add the count to each value if applicable? In this case, 'a' represents the original data var a = [ { id: ...

Splitting Angular modules into separate projects with identical configurations

My Angular project currently consists of approximately 20 different modules. Whenever there is a code change in one module, the entire project needs to be deployed. I am considering breaking down my modules into separate projects for individual deployment. ...

Unable to retrieve the loggedIn value from express.session in a Node.js application

After creating a web application using nodejs and sequelize as the ORM for mysql, I encountered an issue with the loggedIn parameter being undefined when accessing it in different routes despite implementing login functionality with express-session. Here ...

What is the default delay when utilizing the $timeout function in AngularJS?

While looking at the concise information on the AngularJS $timeout documentation page, I noticed that the 'delay' argument is listed as optional. However, when utilizing $timeout without specifying a delay, I observed that a delay is still implem ...

Having trouble with the automatic closing feature of Bootstrap drop down in React?

While using the drop button feature of Bootstrap, I have encountered a situation where it works fine when clicked on, but disabling it by clicking outside using autoClose='outside' does not seem to work as expected. When I click on my hamburge ...

"Experience the power of combining nvD3 with AngularJs to enhance your

Hi everyone, I need some assistance with an issue I'm facing. I can't seem to figure out what's wrong. Here is my JSP page code: <html> <head> <meta charset="utf-8"> <!-- it's important fo ...

Choose a specific option from the dropdown menu using a URL parameter

After reviewing this code snippet: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> // <![CDATA[ $(document).ready(function() { // Parse your query parameters here, and assi ...

Obtain user-inputted dynamic arrays using AngularJS

Is it possible to collect dynamic array input values in AngularJS? I am looking to create a function in AngularJS that can gather all input values in an array and then return that array so it can be displayed anywhere on the page. In PHP, it is possible ...

There is no feedback received upon clicking the login button

I recently implemented a PHP Login system using Joget SSO. Joget provides its own SSO script which I followed to create the login functionality. If the entered username and password match, it displays "login successfully"; otherwise, it shows "login fail ...

Converting important information from elements in an Array into a string separated by commas

Which lodash method or function is best suited for extracting the ids from the array below and creating a comma-separated string out of them? var myArray = [ { tag: 'wunwun', id: 132 }, { tag: 'davos&apos ...

Issue with x-editable nested editable-select not being properly submitted

When I submit the nested editable-select, it does not trigger the onaftersave function ('vm.addOperation()') and also displays the outer editable-select edit form. I only want the nested edit form to show and for the function call to work proper ...

The page reloads automatically following the completion of an ajax request

Hey there, I have a basic form with just a text field. When we submit the form, the data entered in the text field gets stored in the database through ajax. Although the ajax function is working properly and the data is being submitted, the page automatica ...

Ways to obtain user information using a Google access token

Hey there, I'm currently working on implementing Google OAuth2 login and I'm facing a challenge in retrieving user information using either the access token or id token from these URLs when passing the access token in the Authorization header, ...

Best practices for incorporating JavaScript into Angular applications

I am looking to integrate a JavaScript library into my Angular application. After researching various methods, I have decided to incorporate the library found at . I was hoping to create a module named 'plot-function' that would offer a function ...

Exploring Multidimensional Arrays in JSON with jQuery for Parsing

While I have browsed through numerous questions on this platform, I haven't been able to find a solution to my issue with parsing Multidimensional JSON Arrays. Specifically, I am trying to extract data from the "countdown" tag, but my code only goes a ...

Exploring the wonders of JQuery's $.each() method in combination with

My code seems to be facing an issue with the last part, where I have an array containing some data. var dArray = { 'var1': $("#var1").val(), 'var2': $("#var2").val(), 'var3': $("#var3").val(), 'var4' ...

Setting the ariaLabel value in TypeScript is a straightforward process that involves defining the

In my TypeScript React application, I am attempting to dynamically set the ariaLabel value. However, ESLint is flagging an error: Property 'ariaLabel' does not exist on type 'HTMLButtonElement'. I have tried various types but none of t ...

jQuery - Endless paging

My attempt at implementing infinite scrolling on my page seems to have hit a snag. Instead of triggering at the bottom of the page, it's activating when I scroll back to the top. Can anyone shed some light on what might be causing this issue? $(windo ...