Comparing Objects in an Array to Eliminate Duplicates and Make Updates in Javascript

I am working with an array of objects that is structured like this:

0: Object
ConsolidatedItem_catalogId: "080808"
ConsolidatedItem_catalogItem: "undefined"
ConsolidatedItem_cost: "0"
ConsolidatedItem_description: "Test Catalog Item"
ConsolidatedItem_imageFile: "27617647008728.jpg"
ConsolidatedItem_itemNumber: "1234"
ConsolidatedItem_quantity: "1"
ConsolidatedItem_source: "CAT"
ConsolidatedItem_status: "02"
ConsolidatedItem_umCode: "EA"

1: Object
ConsolidatedItem_catalogId: ""
ConsolidatedItem_catalogItem: "undefined"
ConsolidatedItem_cost: "0"
ConsolidatedItem_description: "ALARM,SHUTDOWN SYSTEM,AXIOM,XP3, 0-1500 PSIG, HIGH AND LOW PRES Testing"
ConsolidatedItem_imageFile: ""
ConsolidatedItem_itemNumber: "10008"
ConsolidatedItem_quantity: "1"
ConsolidatedItem_source: "INV"
ConsolidatedItem_status: "02"
ConsolidatedItem_umCode: "EA"

I am attempting to update or remove an object if it is duplicated, preferably by updating the values of the existing object. Here is my current code:

var result = $.grep(finalObject, function(e) {
            return e.ConsolidatedItem_itemNumber == o.ConsolidatedItem_itemNumber;
        });
        console.log(result);
        if (result.length == 0) {
            finalObject.push(o);
            shoppingCounter = finalObject.length;
            $('#numberShoppedItems').text(shoppingCounter);
            console.log(finalObject);
        } else if (result.length == 1) {    
            finalObject.filter(function(x){
                result = x;
                console.log(result);
                return x == result.ConsolidatedItem_itemNumber;

            }); 
        } else {
            alert('Multiples Found');
        } 
    }

I have tried various methods to manipulate and update the data in the objects, but have not had success. Ideally, I would like to merge the quantities of objects with the same CatalogItem_itemNumber if their quantities differ. If you have any guidance on how I can approach this problem, it would be greatly appreciated. I have searched for similar questions, but none seem to address this issue directly. If you know of a relevant question with an answer, please feel free to share the link. No Underscore.js solutions, please.

Answer №1

Once you have identified the corresponding entry, you can easily modify it using the $.extend method.

        $.extend(result[0], o)

This action will directly update the object within the finalObject array.

Alternatively, if you prefer to utilize a filter, you will have to insert the new object into the array.

        finalObject = finalObject.filter(function(x) {
            return x !== result[0];

        }); 
        finalObject.push(o)

In this scenario, any records that do not match the result will be included in the resulting array stored in finalObject. The next step involves adding the new record to the array.

Answer №2

Solution:

1.) Check if the object is not empty.

2.) Utilize .some() on the object to iterate through it.

3.) Verify if the finalObject, now known as e, has a match for the key in the temporary object I create, o.

4.) Update the necessary values and return true;

Note: Initially, I considered removing the object by its index and replacing it with a new object. This can be achieved using .splice() and retrieving the index of the current object within the array.

Below is the updated version:

if (o.ConsolidatedItem_quantity != '') {

    var result = $.grep(finalObject, function(e) {
        return e.ConsolidatedItem_itemNumber == o.ConsolidatedItem_itemNumber;
    });
    if (result.length == 0) {...}
    else {
        finalObject.some(function (e) {
            if(e.ConsolidatedItem_itemNumber == o.ConsolidatedItem_itemNumber){
                var a;
                a = +e.ConsolidatedItem_quantity + +o.ConsolidatedItem_quantity;
                e.ConsolidatedItem_quantity = a.toString();
                document.getElementById(o.ConsolidatedItem_itemNumber).value=a;
                return true;
            };
        });
    }
}

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

Upload files via Ajax request is required

I am in the process of trying to upload a binary file to a server while avoiding a full page refresh when the server responds. I must admit, I am not well-versed in this area and I understand if my approach needs some adjustments. This is how I have appro ...

Ways to effectively manage multiple asynchronous operations while retrieving emails and attachments using IMAP and JavaScript

Currently, I am utilizing the IMAP library along with JavaScript to retrieve emails from a server. This is my approach: Retrieve emails based on email address, subject, and a specified time frame. Determine the total number of emails received. For each e ...

Error in Browserify Express App: Unexpected token while parsing the file

I have been attempting to browserify a javascript file. When I run the command: browserify global.js -o bundle.js An error message is returned: Error: Parsing file C:\ocquiz\public\javascripts\global.js: Unexpected token (756 ...

What are the steps to transition from @zeit/next-sass deprecation?

Is there a way to transition and modify the next.config.js file to switch from using @zeit/next-sass to leveraging Next.js's built-in support for Sass? Check out this link for more information: https://www.npmjs.com/package/@zeit/next-sass const withS ...

Cypress - Mastering negative lookaheads in Regular Expressions

While experimenting with Cypress, I encountered an issue regarding a filter test. The goal is to verify that once the filter is removed, the search results should display values that were filtered out earlier. My attempt to achieve this scenario involves ...

Guide to Deactivating the ENTER Key Functionality in React Material UI Autocomplete Form

My React component features a Material UI Autocomplete form that is working perfectly, except for one issue - when the user hits ENTER, the input field gets cleared. I simply want to prevent the input field from being cleared when ENTER key is pressed. Des ...

The system displayed an 'Error' stating that the variable 'index' is defined in the code but is never actually utilized, resulting in the (no-unused-vars) warning

I have configured eslint and eslint-plugin-react for my project. Upon running ESLint, I am encountering no-unused-vars errors for every React component in the codebase. It seems like ESLint is not properly identifying JSX or React syntax. Any suggestions ...

Why is my console showing a SyntaxError with JSON.parse and an unexpected character?

I am facing an issue. When I attempt to call a PHP page for some data with specific requested parameters using AJAX asynchronous call, I encounter the following error: SyntaxError: JSON.parse: unexpected character var jsonData = $.ajax({ u ...

Angular 2 partial static routing parameters with customizable features

Can an angular 2 routing configuration include a partial-static parameter? Currently, I am using a classic parameter setup like this: const routes: Routes = [ { path: ':type/fine.html', pathMatch: 'full', redirectTo: &ap ...

Get a Google Sheets file in CSV format

Currently, I am in the process of developing cloud functions for pushing data to Google AutoML. I have successfully created a function to generate the necessary data. However, for the next phase, I am curious about the possibility of downloading a Google ...

How can I use conditional 'if' statements to import separate modules in Node.js ES Modules?

Recently, I tried out a tutorial that utilises CommonJS for exporting/ importing different keys depending on the environment. However, I am wondering how I can make it compatible with ES Modules import/export instead? This is the code snippet provided in ...

dojo combobox with data loaded dynamically from JSON

I am facing an issue with populating a Combobox dynamically using a jsonRest from a cross-origin request. While I have managed to do it statically (if that's the correct term), I am struggling to implement it for multiple cases. This is just a small ...

Generating a constantly evolving 3D model and keeping it current within a web browser

My website already has a large user base, and I am looking to create a 3D visual representation of data on one of the pages. This model needs to be easily updatable based on each user's database information (imagine a square board with a ball whose po ...

When using PHP, JavaScript, and HTML, you can trigger an image upload immediately after choosing a file using the

I currently have a small form with two buttons - one for browsing and another for uploading an image. I feel that having two separate buttons for this purpose is unnecessary. Is there a way to combine the browse and upload functions into just one button? ...

What could be the reason that the painting application is not functioning properly on mobile devices?

I am facing an issue with my painting app where it works perfectly on desktop browsers but fails to function on mobile devices. I tried adding event listeners for mobile events, which are understood by mobile devices, but unfortunately, that did not solve ...

I'm having trouble with my bootstrap dropdown and I've exhausted all of my options trying to fix it based on my current understanding

My dropdown menu is not working despite adding all necessary Bootstrap CDN and files along with the jQuery script. Even with the table being handled by JavaScript, the button does not respond when clicked repeatedly. I suspect the issue lies within the han ...

Sending a POST request to a Flask server using Stripe and AJAX

I am attempting to implement a function that triggers an ajax request when a stripe form is submitted. However, using the .submit() method doesn't seem to be working as expected. Here is my current code: HTML <form action="/download_data" method= ...

What is the best way to display an image along with a description using Firebase and next.js?

I am currently utilizing Firebase 9 and Next.js 13 to develop a CRUD application. I am facing an issue where the images associated with a post are not correctly linked to the post ID. Furthermore, I need guidance on how to display these images in other com ...

The HTML Style for implementing HighChart title text does not work when exporting files

I have inserted the <br/> and &nbsp; HTML tags into the HighChart titles. The style changes successfully appear in the chart view, but unfortunately, when exported as PNG or JPEG images, the text style fails to apply in the resulting images. To s ...

Operating a React application in the background

Being a novice in the world of deploying front-end code, I have encountered a challenging situation that requires assistance. I am currently working on a React App that needs to be operated as a background process. However, I'm facing some confusion r ...