Add a new value to an object and ensure that only the unique value is appended to the first

I have a scenario where I have 2 objects, and I need to add a new key value pair to only the first matching object of its kind.

Obj1
[{
buyDate: "yesterday",
productId: "0001",
consumerId: "John",
price: 10
// add new key value pair here
},
{
buyDate: "today",
productId: "0001",
consumerId: "John",
price: 10
},
{
buyDate: "yesterday",
productId: "0002",
consumerId: "Doe",
price: 7
}]
Obj2
{
productId: "0001",
consumerId: "John",
quantity: 4
}

Within Obj1, when the productId and consumerId matches, I want to add a new key value pair from Obj2 that has the same productId and consumerId to the first occurrence of 0001 and John.

I've encountered a roadblock at this point.

     let newObj2 = {};
      if (Obj1) {
        Obj1.forEach((e) => {
          newObj2[e.consumerId] = e;
        });
      }

      let newData = Obj1.map((e) => {
        return {
          ...e,
          quantity: Obj2[e.consumerId]?.quantity
            ? Obj2[e.consumerId]?.quantity
            : 0,
        };
      });

If anyone could provide guidance on how to accomplish this task, I would greatly appreciate it. Thank you in advance

edit: There might be some errors in the dummy data provided

Answer №1

Implement Array.find to locate the specific element within the array being searched by following these steps:

const records = [
  { timestamp: "yesterday", productID: "0001", customerID: "John", price: 10 },
  { timestamp: "today", productID: "0001", customerID: "John", price: 10 },
  { timestamp: "yesterday", productID: "0002", customerID: "Doe", price: 7 }
];
const itemToFind = {
  productID: "0001", customerID: "John", quantity: 4
};
let foundItem = records.find(function(record) {
  return record.productID === itemToFind.productID && record.customerID === itemToFind.customerID
});
if (foundItem === undefined) {
  // item not located
} else {
  foundItem.quantity = itemToFind.quantity;
}
console.log(records);

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

The authentication0 router fails to initiate navigation

I'm currently using Auth0 in combination with Angular 2. The issue I am encountering is that my login code isn't redirecting to the home page after authentication. Based on my understanding, Auth0 does not handle the redirection process itself. ...

The integration of Tinymce and Vuetify dialog is causing issues where users are unable to input text in the source code editor or add code samples

Having an issue with the Vuetify dialog and TinyMCE editor. Upon opening the dialog with the editor inside, certain functionalities like Edit source code or Insert code sample are not working as intended. Specifically, when attempting to use one of these p ...

Adding flair to the encompassing container

Below is the HTML code that I am working with: <div class="um-field field-date"> <p class="form-row " id="date_field"> <label class="date"> <input data-label="Date" data-value="" type="date" class="input-date um-frontend-f ...

Highlighting table column when input is selected

I am working with a table where each <td> contains an <input>. My goal is to apply the class .highlighted to all the column <td>s when an <input> is being focused on. Additionally, I want to remove this class from all other columns ...

Vue: Load page content only after the route change is complete

Every time I visit a new route within the current session, I notice that the page loads and then takes about 2 seconds for the styles to be applied. This delay causes what is commonly known as CSS flashing or FOUC (Flash of Unstyled Content), which ultimat ...

Refreshing a div's content with a single click to update the page

I'm experimenting with elements above my head and striving to absorb new knowledge. In my admin page, I use jQuery to reveal a hidden div that displays another page within it. Here's how I achieve this: $(document).ready(function(){ $("a#fad ...

What is the best way to incorporate padding into an Angular mat tooltip?

I've been attempting to enhance the appearance of the tooltip dialog window by adding padding. While adjusting the width and background color was successful, I'm encountering difficulties when it comes to styling the padding: https://i.sstatic.ne ...

What is the best way to check for incorrect or missing values when comparing two Arrays?

Can you help me with comparing two arrays, $original and $duplicate? Here is the content of my original array: print_r($original); Array ( [0] => cat423 [1] => dog456 [2] => horse872 [3] => duck082 ) And this is my duplicate array: pr ...

Looking to design an interactive grid for generating dynamic thumbnails

I am a beginner in the field of web development and I have a desire to create a website for showcasing my portfolio. This website should feature project thumbnails along with brief descriptions, all of which should be displayed dynamically. Although I poss ...

Fetching data using an Ajax request in PHP is encountering issues, whereas the same request is successfully

I am experiencing an issue with a simple Ajax call in ASP.NET that works fine, but encounters a strange DOM Exception when I insert a breakpoint inside the onreadystatechange function. Can anyone explain why ASP.NET seems to have some additional header log ...

Coming back from retrieving data from an API

I'm having trouble with a function that performs a POST request to retrieve access tokens from an API. Although the function successfully prints the token to the console, I haven't been able to figure out how to properly parse and save the access ...

Vue.js problem with conditional rendering using v-if

I'm struggling to grasp the concept behind how v-if functions. My goal is to dynamically hide buttons in the navigation bar based on the user's authentication status and current page. Specifically, I want the "My Account" button to be displayed w ...

Prevent the href from navigating to the next page when a doubleclick event listener is triggered

In my project, I am using an anchor tag that redirects to another page. However, if the user double clicks on it, I want to prevent the default behavior and stop the redirection. <a href="{location}">My Link</a> element.addEventListen ...

Surprising pause in the menu transition animation

Currently, I am in the process of developing a menu that seems to have some flaws. One issue is that it appears a bit choppy, but the more concerning problem is the half-second delay after clicking an item before it animates. The concept behind this menu ...

Discover the hidden truth: Unveiling the enigma of React

I'm currently learning React and I've been working on some apps to enhance my skills and deepen my understanding. Right now, I am facing a challenge where I need to incorporate the logged user information into the Redux state. However, whenever I ...

Pattern matching to find occurrences of their, their's, theirs, theirs, and theirs' using regular expressions

I am attempting to create a regex in JavaScript that matches the different forms of "their" and its possessive form. Currently, I have their|their(?:'?s), which successfully matches their, theirs, and their's; but does not match theirs'. C ...

Are you experiencing issues with the cipher update when using the crypto library?

When using the crypto module for string encryption and the passed string is not 16 bytes, I expected the cipher.update() function to automatically add padding and create a 16-byte string. However, during debugging, cipher.update returned an empty string. I ...

Expanding div width with jQuery as a percentage

Currently, I am facing a dilemma as I try to devise an equation for expanding the width of a div based on its current height. The Scenario Within this situation, there is a div that features a background image set to "contain." The original background ima ...

The Slide Out Menu functioned properly in HTML, but it seems to be malfunctioning when implemented in PHP

I recently implemented a slide-in and out menu with a hamburger icon to open it and an X icon to close it. The functionality was perfect until I integrated it into PHP and WordPress. Initially, I placed the script in the header section before the meta tags ...

Issue with setInterval function execution within an Angular for loop

My goal is to dynamically invoke an API at specific intervals. However, when attempting to utilize the following code snippet in Angular 7, I encountered issues with the interval timing. I am seeking a solution for achieving dynamic short polling. ngOnIn ...