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

Building a Many-to-Many Relationship in Node.js Using Sequelize.js

As I utilize the sequelize node.js module to structure schema in Postgres SQL, I have defined two schemas for Project and my users. Project Schema module.exports = function(sequelize, DataTypes) { var project = sequelize.define('project', { ...

Troubles arising while submitting data from AngularJS to Amazon S3

I am currently in the process of developing an application using the MEAN (MongoDB, Express, AngularJS, node.js) stack where I need to upload image files to Amazon S3. Here is my approach: Initially, an http get request is sent to my API which outlines th ...

Enhancing an array of objects by incorporating properties using map and promises

I am encountering an issue with assigning a new property to each object in an array, which is obtained through an async function within a map method. Here is the code snippet that I am using: asyncFunction.then(array => { var promises = array.map(o ...

What is the best way to manipulate arrays using React hooks?

Struggling with updating arrays using hooks for state management has been quite a challenge for me. I've experimented with various solutions, but the useReducer method paired with dispatch on onClick handlers seems to be the most effective for perform ...

Implementing Partial Login and Registration Views using AngularJS in conjunction with MVC5 and ASP.NET Identity

Embarking on the journey of creating a Single Page Application with log-in/register functionality using MVC5, ASP.NET Identity, and Angular feels like diving into a vast ocean of web development technologies. Despite being new to this realm, I delved into ...

Troubleshooting issue with Gulp watch on Node v4.6.0

I'm currently facing a frustrating situation. I had a project up and running smoothly with a functioning gulpfile.js file, everything was perfect until I updated node to version 4.6.0. When I tried to report this issue on Gulp's git repository, t ...

The console indicates that the state's arrays have been filled, yet I'm unable to retrieve the object[0]

In my code, the functions that populate the state are called on component will mount. When I log the state on the render, this is what I observe in the log. The log clearly shows that the arrays in the state have been populated, although there seems to be ...

Is it possible to replicate an HTML table using JavaScript without including the headers?

Discover a JavaScript snippet in this stack overflow post that allows you to create a button for automatically selecting and copying a table to the clipboard. When pasting the data into an Excel template, my users prefer not to include the header informat ...

React and Axios: Overcoming CORS Policy to Connect with Java/SpringBoot REST Backend Service

As a first-time user of Axios to connect to my Java/SpringBoot Rest GET service on localhost:8080, I am using React and node.js. My goal is to successfully retrieve the REST data but encountered the following error: Failed to compile src\App.js Lin ...

What steps do I need to take to retrieve data in a JSON array based on its

Hello, I could really use your assistance with a problem I'm having. Here is the scenario: I have a JSON array that looks like this: "category" : [ { id: 1, product: [{id : product_1, type : ball}] }, { id : 2, product :[{id : prod ...

The tablet is having trouble playing the mp3 audio file

When clicking on an mp3 audio file, I want the previous file to continue playing along with the new one. While this works perfectly on browsers with Windows machines, there seems to be an issue when using a tablet. The second mp3 stops playing when I clic ...

Issue with Jest while testing a React component library that has been bundled without the React library

I have extensive experience building React applications and decided to create a React Component library. After researching different approaches, I chose to use Webpack and Babel for bundling without including React itself in the library. This decision was ...

Refresh the div by clicking it

$(window).load(function() { $("#Button").click(function() { alert('clicked') $("#div").load(" #div > *"); }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <script ...

Puppeteer: Interacting with login dialog box fields

I am currently facing an issue while attempting to generate a .pdf file from a specific page on our Intranet using Puppeteer and Headless Chrome within Node.js. Generating a .pdf file from a regular webpage poses no challenge, but I am encountering diffic ...

Tokenizer method utilizing strings

Imagine a scenario where strings adhere to this specific format: id-string1-string2-string3.extension In this case, id, string1, string2, and string3 can all vary in length, with extension being a standard image extension type. To illustrate, here are a ...

Discovering the power of Next.js Dynamic Import for handling multiple exportsI hope this

When it comes to dynamic imports, Next.js suggests using the following syntax: const DynamicComponent = dynamic(() => import('../components/hello')) However, I prefer to import all exports from a file like this: import * as SectionComponents ...

Vue has detected an error during rendering: "TypeError: state.actionInfo.find is not a function"

Using vue.js's cli, I created a basic data register application. The application utilizes lookback.js api with vue cli. The application consists of three pages: show, add, and edit. While the show and add pages function correctly, issues arise when ...

Using Express.js with synchronous functions can cause the web application to freeze

While developing an app using Express, I realized that I made a mistake regarding my usage of Promises. Here is the code in module.js: module.exports = function(arguments){ for(let k =1; k < something.length; k++){ let options = { & ...

Using Vue to display a Div inside a TD element of a table does not result in a reactive behavior

I am encountering an issue with a table where the last column contains a div with three options (View, Edit, and Delete). This submenu is initially hidden, but when clicking on the options button in the last column of the table, the array used to control i ...

What causes Bootstrap to malfunction when the route contains double slashes?

When using /something, everything works fine, but when switching to /something/somethingelse, Bootstrap fails to function. It seems that the number of "/" characters in the route is causing this issue, rather than the content inside the .ejs file. Here is ...