简体   繁体   中英

Target an object in an array by one of its key's values (a product id) to change another of its values (increase count)?

I'm working on a shopping basket with local storage. This is the step during which I am checking whether a similar product is already in the basket/local storage.

I'm not sure how to target the specific object of color+model combo to increase the count.

for (let loggedProduct of products) {
  console.log('for of 'exists' loop runs'); // DEL
  if (loggedProduct.id === newAdd.id) {
    if (loggedProduct.color === newAdd.color) {
      product_exists = true;

      // loggedProduct.count is a string. Work around to make it a number:
      loggedProduct.count = parseInt(loggedProduct.count);
      loggedProduct.count += 1;

      // I would like to make the part above specific to the id/color combo, but I'm not sure how.
      }
    }

This was my solution after redditers helped me find the thing I was missing.

for (let loggedProduct of products) {
      if (
        loggedProduct.id === newAdd.id &&
        loggedProduct.color === newAdd.color
      ) {
        product_exists = true;
        // loggedProduct.count is a string. Work around to make it a number:
        loggedProduct.count = parseInt(loggedProduct.count);
        loggedProduct.count += 1;

        // console.log('count after: ', loggedProduct.count); // DEL
      }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM