Locate an object for editing or adding changes

My scenario involves the existence of an object named productCounts

[{provisioned=2.0, product=str1, totalID=1.0}, 
 {product=str2, provisioned=4.0, totalID=3.0}, 
 {provisioned=6.0, product=str3, totalID=5.0}]

In addition, there is an array labeled uniqueProduct

[str1, str2, str3, str4]

The objective here is to iterate through a dataset in order to retrieve the count of totalID, then add it to the respective product's totalID. If the product does not exist, it should be included in the object.

var countID = 0;

uniqueProduct.forEach(
  currentproduct => {
    countID = 0;
    for (var i = 0; i < shtRng.length; ++i) {
      if (shtRng[i][ProductCol].toString() == currentproduct) { // && shtRng[i][IDcol].toString().length>4){
        countID++;
      }
    }
    if (countID == 0) {
      return;
    }

    console.log(currentproduct + ": " + countID);
  }
)

This code effectively returns the countID per product within uniqueProduct

Instead of just logging the outcome, the aim is to incorporate it into the object as shown below... when the current unique product is absent from the productCounts object, it should be added accordingly.

let obj = productCounts.find((o, i) => {
    if (o.product == currentproduct) {
        productCounts[i] = { product: currentproduct, totalID: productCounts[i].totalID+countID, provisioned: productCounts[i].provisioned };
        return true;
    } else {
        productCounts.push({ product: currentproduct, totalID: countID, provisioned: 0 });
        return true;
    }
}); 

Although theoretically sound, the execution seems to miss certain records or duplicates products. How can the object be updated accurately?

The anticipated outcome is for the object to resemble the following:

[{provisioned=2.0, product=str1, totalID=35.0}, {product=str2, provisioned=4.0, totalID=8.0}, {provisioned=6.0, product=str3, totalID=51.0}, {provisioned=6.0, product=str4, totalID=14.0}]

Answer №1

When using the find() method, the argument passed should be a function that evaluates to a boolean when the element meets certain criteria. It is important to note that the result of this evaluation should be used in an if statement and not within the condition function itself.

let obj = productCounts.find(o => o.product == currentProduct);
if (obj) {
    obj.totalId += countID;
} else {
    productCounts.push(productCounts.push({ product: currentproduct, totalID: countID, provisioned: 0 });
}

By the way, it would make your life much easier if you were to utilize an object with product names as keys rather than an array of objects. You can easily convert the array of objects into such an object:

let productCountsObj = Object.fromEntries(productCounts.map(o => [o.product, o]));
if (currentProduct in productCountsObj) {
    productCountsObj[currentProduct].totalID += countID;
} else {
    productCountsObj[currentProduct] = { product: currentproduct, totalID: countID, provisioned: 0 };
}

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

Angular controller filter issue causing unexpected behavior

Within my Angular controller, I am utilizing a filter in a specific manner. My intention is to filter only $scope.codeSubFiltered, while leaving $scope.codeSub unaffected. However, after applying the filter, both $scope.codeSub and $scope.codeSubFiltered ...

Issue encountered when attempting to assign an action() to each individual component

I'm facing an issue with the button component I've created. import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'app-button', template: ` <ion-button color="{{color}}" (click)="action()"&g ...

Looking to transform a string into JSON format using LogStash

Currently, I am facing an issue with how Logstash is handling a specific field in JSON format. The problem arises from Logstash treating this field as a string due to the presence of quotes around the value. My goal is to have Logstash interpret the conten ...

Utilizing ID for Data Filtering

[ { "acronym": "VMF", "defaultValue": "Video & Audio Management Function", "description": "This is defined as the Video and/or Audio Management functionality that can be performed on a Digital Item. The Video & Audio M ...

Create unique identifiers for the TD elements of Viz.js that will be displayed within the SVG elements

Below is the DOT code snippet in Viz.js that I am working with: digraph G { node [fontname = "font-awesome"]; 17 [id=17, shape="hexagon", label=<<TABLE BORDER="0"> <TR><TD>undefined</TD></TR> <TR><TD>[47-56]< ...

What could be preventing the jQuery from showing the JSON response?

I am having an issue with a jQuery script that is supposed to pull a quote from an API in JSON format and display it on the page. However, for some reason, I am unable to retrieve data from the API. Can you help me figure out what is wrong here? Thank yo ...

Deliver compressed data in gzip format from a Node.js server to the client using socket.io

I am currently facing an issue regarding determining whether the data being sent back to the client is compressed in gzip format or not. Upon examining my server's output from the command line, I notice the following: debug - websocket writing 3:::{" ...

Unusual actions from the jQuery Steps extension

I am currently utilizing the jQuery Steps plugin (FIND IT HERE). The issue I'm facing lies within an IF statement that is causing the wizard to return to the first step instead of staying on the current indexed step. While all other IF statements are ...

Hold on for the useState object to contain a value

Created a custom hook that fetches the user's location and determines the nearest marker on a map based on that information. Initially, it returns the default value of useState. The response looks like this: { coordinates: { lat: '', lng: ...

Add three rows without clicking, then click once to add one row at a time

Seeking guidance on how to defaultly display 3 rows after adding and removing rows, as well as applying the removal of a default set of 3 rows using JavaScript. Any valuable ideas are appreciated! Example needed:- https://i.sstatic.net/DF8Wn.png $(docum ...

How to Retrieve a Remote File in Angular using $http.get() with OAuth Authentication

I have a unique situation where my users possess private files that require downloads by authenticated users. The server I am using initially downloads a file from S3 utilizing its own set of S3 app_id and secret_token credentials. Once the file has been d ...

Updating information within AngularJS select boxes

On my page, I have 3 select boxes. When a user selects an option in the first select box, I want the options in the second select box to update based on the value selected in the first one. Similarly, I want the options in the third select box to change w ...

The AWS lambda function is failing to process the POST variables

Despite working correctly in the AWS Lambda dashboard, my lambda function seems to be ignoring any json data that is posted to it. When testing with curl: curl -X POST -H "Content-Type: application/json" -d '{ "email":"[email protected]", " ...

Having issues with Angular Material, specifically with mat-list-item and routerLinkActive not functioning as expected

Currently, I am working with a navigation view that utilizes the MatSidenavModule. The issue I am encountering is on mobile screens. When I click a mat-list-item, the mat-sidenav closes as expected. However, upon opening the mat-sidenav again, Material alw ...

Enter key not triggering submission in jQuery UI autocomplete field

I'm currently working on implementing the autocomplete feature following a tutorial, and while it's functioning, I'm facing an issue with submitting the form when the user selects an item and hits enter. Below is the Coffeescript code that I ...

Hover effect not displaying upon mouse exit

I am working on a feature where a series of images change when hovered over, with a div animating as an overlay on the image. Here is the code snippet: // hiding overlays initially $(".mini-shop .item .image a div").hide(); // toggling overlay and second ...

Having a problem with doParallel and foreach. I am able to set cores, but they are not executing as expected

I am facing a challenge with analyzing a large dataset which consists of approximately 40 million rows and 4 columns. My objective is to conduct a Fisher test on the data within each row. Here is an example snippet of the dataset: refAppleBase altAppleBa ...

Retrieving data from an external PHP script

I'm facing an issue with retrieving results from a PHP file after submitting a form: index.php (located at ) <form id='loginForm' action='http://domain1.com/mail.php' method='POST'> <input id=&apo ...

Assigning a click event to an element within CKEditor

Looking to add a click event to an element in ckeditor4-angular for custom functionality <div class="fractional-block" id="fractional-block"><span>5</span><svg height="5" width="100%"><line ...

Having trouble with expressJs router.post() not functioning properly with multiple middleware, resulting in an [object Undefined] error

I have been working on developing a REST API for my users, utilizing express-validator for validation before adding the user to the database. However, I encountered an issue while chaining my middleware in the router.py file which resulted in the error Err ...