Merge both arrays together following the application of the filter technique

Having trouble displaying the cart page showcasing the products added by users. I have two arrays: one containing product details and another with cart product details showing product IDs and quantities selected by users.

productDetails: [
            {
              productID: 1,
              productTitle: 'Product Title 1',
              productPrice: 2000
            },
            {
              productID: 2,
              productTitle: 'Product Title 2',
              productPrice: 5000
            },
            {
              productID: 3,
              productTitle: 'Product Title 3',
              productPrice: 1000
            },
            {
              productID: 4,
              productTitle: 'Product Title 4',
              productPrice: 10000
            }
          ],

CartProducts array contains:

cartProducts: [
            {
              productID: 1,
              quantity: 5,
            },
            {
              productID: 3,
              quantity: 2,
            }
          ]

I have successfully filtered all the products that the user has selected. Function below provides the details of products with ID 1 and 3, but now I want to merge this information into a new array adding the quantity attribute as well.

newArray: [
            {
              productID: 1,
              productTitle: 'Product Title 1',
              productPrice: 2000,
              quantity:5
            },
            {
              productID: 3,
              productTitle: 'Product Title 3',
              productPrice: 1000,
              quantity:5
            }
          ]

I hope my query is clear. I am attempting to solve this using the map method in JavaScript without success.

Best Regards,

Answer №1

You could apply the map() method following a filter() operation to include a quantity property for each item.

const productDetails = [{ productID: 1, productTitle: 'Product Title 1', productPrice: 2000 }, { productID: 2, productTitle: 'Product Title 2', productPrice: 5000 }, { productID: 3, productTitle: 'Product Title 3', productPrice: 1000 }, { productID: 4, productTitle: 'Product Title 4', productPrice: 10000 }];
const cartProducts = [{ productID: 1, quantity: 5 }, { productID: 3, quantity: 2 }]; 

function updateCartItemDetails() {
  return productDetails
    .filter(el => cartProducts.some(f => f.productID === el.productID))
    .map(item => ({
      ...item,
      "quantity": cartProducts.find(f => f.productID === item.productID).quantity
    }));
}

console.log(updateCartItemDetails());

Alternatively, you may utilize the reduce() function.

const productDetails = [{ productID: 1, productTitle: 'Product Title 1', productPrice: 2000 }, { productID: 2, productTitle: 'Product Title 2', productPrice: 5000 }, { productID: 3, productTitle: 'Product Title 3', productPrice: 1000 }, { productID: 4, productTitle: 'Product Title 4', productPrice: 10000 }];
const cartProducts = [{ productID: 1, quantity: 5 }, { productID: 3, quantity: 2 }]; 

function updateCartItemDetails() {
  return productDetails.reduce((acc, curr) => {
    let item = cartProducts.find(f => f.productID === curr.productID);

    if (item) {
      acc.push({ ...curr,
        "quantity": item.quantity
      });
    }

    return acc;
  }, []);
}

console.log(updateCartItemDetails());

An alternative approach would be using map() directly on cartProducts.

const productDetails = [{ productID: 1, productTitle: 'Product Title 1', productPrice: 2000 }, { productID: 2, productTitle: 'Product Title 2', productPrice: 5000 }, { productID: 3, productTitle: 'Product Title 3', productPrice: 1000 }, { productID: 4, productTitle: 'Product Title 4', productPrice: 10000 }];
const cartProducts = [{ productID: 1, quantity: 5 }, { productID: 3, quantity: 2 }]; 

function updateCartItemDetails() {
  return cartProducts.map(item => ({
    ...productDetails.find(f => f.productID === item.productID),
    ...item
  }));
}

console.log(updateCartItemDetails());

Answer №2

Utilize map and object spread to merge the contents of both arrays:

let mergedArray = cartProducts.map(cart => ({
  ...cart,
  ...productDetails.find(prod => prod.productID === cart.productID)
}));

Answer №3

Transform the productDetails data into a Map structure called productDetailsMap, where the key is the productID.

Loop through the cartProducts array using Array.map() to retrieve each product from productDetailsMap based on its productID, then merge them by spreading technique into a new object.

const productDetails = [{"productID":1,"productTitle":"Product Title 1","productPrice":2000},{"productID":2,"productTitle":"Product Title 2","productPrice":5000},{"productID":3,"productTitle":"Product Title 3","productPrice":1000},{"productID":4,"productTitle":"Product Title 4","productPrice":10000}]
const cartProducts = [{"productID":1,"quantity":5},{"productID":3,"quantity":2}]

const productDetailsMap = new Map(productDetails.map(o => [o.productID, o]))

const result = cartProducts.map(o => ({
  ...productDetailsMap.get(o.productID),
  ...o
}))

console.log(result)

Answer №4

If you're looking for a solution, you might want to consider the following approach:

retrieveCartItemInfo() {
    return this.itemsInCart.map(item => {
         let details = this.itemDetails.find(detail => detail.itemID === item.itemID)
         return {...item, ...details}
    })
}

I hope this suggestion proves useful!

Answer №5

To easily transfer property-value pairs from productDetails to cartProducts based on matching productID, you can utilize the Object.assign() method:

let productDetails = [
            {
              productID: 1,
              productTitle: 'Product Title 1',
              productPrice: 2000
            },
            {
              productID: 2,
              productTitle: 'Product Title 2',
              productPrice: 5000
            },
            {
              productID: 3,
              productTitle: 'Product Title 3',
              productPrice: 1000
            },
            {
              productID: 4,
              productTitle: 'Product Title 4',
              productPrice: 10000
            }
          ];

let cartProducts = [
            {
              productID: 1,
              quantity: 5,
            },
            {
              productID: 3,
              quantity: 2,
            }
          ];
cartProducts.map(cart => Object.assign(cart, productDetails.find(product => product.productID === cart.productID))  )
console.log(cartProducts)

Answer №6

for each cartProduct in cartProducts, find the product details with matching productID
and return an object with the product details and the quantity from cartProduct

Consider adding null checks if necessary.

Answer №7

Your code is experiencing an issue here:

cartItemDetails() {
      return this.productDetails.filter(
        el => this.cartProducts.some(f => f.id === el.productID),
      );
    },

The variable f, which represents a cartProducts item, does not have an id property.

I believe you intended to use f.productID instead.

Here is a solution for adding the quantity property using the map function :

this.productDetails = cartItemDetails().map((element) => {
  for (let e of this.cartProducts) {
    if (e.productID === element.productID) return {...element, quantity: e.quantity}
  }
})

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

Having issues with displaying options in Select2 within a Vue Component?

I have successfully created a Vue component that generates options for a select dropdown as shown below: <select ref="subdomain_id" name="subdomain_id" id="newEvidenceSubdomain" class="form-control" :class=&qu ...

Display toggle malfunctioning when switching tabs

I am currently working on implementing a search function with tabbed features. Everything seems to be displaying correctly without any errors. However, the issue arises when I try to click on any tab in order to show or hide specific content from other tab ...

If the socket cannot be found, an error callback will be activated

Below is the method I am using to send a message to a targeted socket connection. socket.broadcast.to(socketid).emit('message', JSON.stringify(data)); If the specified "socketid" does not exist, is there a mechanism in place to capture the erro ...

The Vue Watch feature fails to trigger when incorporating axios

Hello everyone, I am facing an issue with my code that involves fetching data from a database using axios. The problem is that the watch function is not triggering in the .then() block. Below is the snippet of code I am currently working with. Thank you ...

Managing several items within one function

I am working with a json file that contains similar data sets but different objects. { "AP": [{ "name": "Autogen Program" }, { "status": "Completed" }, { "start": "2014-05-05" }, { ...

I'm having trouble grasping the concept of serving gzip-compressed JavaScript and CSS files

Why is it important to serve compressed JavaScript and CSS files? I understand that it reduces file size, but does the browser/webserver have to decompress them to read them? It's been mentioned that the webserver handles the compression. Does this me ...

What are the steps for implementing custom edit components in material-react-table?

I am currently using the official material-react-table documentation to implement a CRUD table. You can find more information at this link: . However, I encountered an issue while trying to utilize my own custom modal components for the "create new" featur ...

Mesh in THREE.js experiencing jittering issues when global position is set

I have created a function called moveToPoint in order to set the global position of an object. This function takes in a world point x y z, converts it to the local coordinate system, and then updates the object.position to go to that new local coordinate. ...

Mastering the asynchronous nature of Node.js with async/await techniques

Is there a way to synchronize the creation of my customers' shopping cart and the insertion of items using a dynamically generated session id? It seems like the issue lies with the order in which the table (cart) is created. Could someone assist me wi ...

Preventing event propagation in Angular when clicking

What is the best way to call an Angular function within my jQuery code? I attempted to do so with the following: $(document).on('click', '.myBtn', function(e) { angular.element($(".someClass")).scope().clearBtnItems(); e.stop ...

Release a stationary element upon scrolling down the page

I have a calculator feature on my website which was coded in php. At the end of this calculator, there is a section that displays the results. While the results div works properly on desktop, I am looking to implement a fix for mobile devices. Specificall ...

Ways to activate a javascript function upon the visibility of a button changing

Utilizing a third-party JS and HTML library that I prefer not to update. The HTML contains an "apply all" button, and my goal is to have this button clicked when it is visible. <div class="confirm" ng-show="newFilters.length"> .... <butto ...

Trouble with ID.Replace function

Within my gridview, I am trying to extract the ID of a row when it is clicked. The ID returned looks like gvBookingsRow_5. $(".gvBookingsRow_").click(function (e) { ShowBookingComment($(this).attr("ID")); ...

Troubles arise when compiling TypeScript to JavaScript

I have been experimenting with TypeScript, specifically for working with classes. However, I am facing an issue after compiling my TS file into JS. Below is the TypeScript code for my class (PartenaireTSModel.ts): export namespace Partenaires { export ...

Guide on inserting text within a Toggle Switch Component using React

Is there a way to insert text inside a Switch component in ReactJS? Specifically, I'm looking to add the text EN and PT within the Switch Component. I opted not to use any libraries for this. Instead, I crafted the component solely using CSS to achie ...

Passing Javascript variable dynamically to an AngularJS function

Is it possible to dynamically pass only a JavaScript variable to an Angular function without using a scope variable in certain scenarios? Please refer to the code snippet on this JSFiddle link. <div style="border:solid;color:red;Margin-bottom:4px;"& ...

What is the best way to invoke an external JavaScript source using another JavaScript source?

I am trying to connect 2 different files together. file1.php and document.html file1.php has the following code in it: document.writeln('< script src="https://www.googletagservices.com/tag/js/gpt.js"> googletag.pubads().definePassback ...

What is the best way to activate an event listener only after a button has been clicked?

Currently, I am developing a game that includes a timer and an event listener that notifies the user not to switch tabs. However, I am facing an issue where the event listener triggers before the game's start button is clicked. Is there a way in JavaS ...

Distinguishing Between Angular and Ajax When Making Requests to a NodeJS Server

Trying to establish communication between an Angular client and a NodeJS server. Previous method using JQuery $.ajax({ url: "/list", type: "POST", contentType: "application/json", dataType: "json", success: function(data) { console.log("Data ...

What is the best way to change the order of my array by increments of two?

My goal is to merge and display two arrays, A and B, in a specific order as shown below: A0 B0 A1 B1 B2 A2 B3 A3 A4 B4 A5 B5 B6 A6 B7 A7 This is the current code I have developed: for($i = 0; $i < count($a); $i++) { if(...) { $mergeArra ...