How to remove multiple items when item.properties match?

105 views Asked by At

Currently I have a selects on a product page ie:

Which then pushes to the cart like so

Is there a way to ensure when any of the items with the same Rope_ID gets removed they all get removed?

Here is an example of cart.js - json

{
  "items": [
    {
      "id": 47172705059137,
      "properties": {
        "Rope_ID": "1699578662053"
      },
      "quantity": 1,
      "variant_id": 47172705059137,
      "key": "47172705059137:78613041670c5e8886d92429b00d14cd",
    },
    {
      "id": 46529331331393,
      "properties": {
        "End 1": "Splice Eyelet End w/-Thimble",
        "End 2": "Heat Sealed Cut",
        "Rope_ID": "1699578662053"
      },
      "quantity": 1,
      "variant_id": 46529331331393,
      "key": "46529331331393:2f19286fc8bd365ed585af1c61c42815",
    }
  ],
}

What was the best way around this? - I haven't worked that much with arrays and would greatly appreciate help.

1

There are 1 answers

2
Vinith_jk_bro On

to make sure the items with the same "Rope_ID" gets removed together, you can iterate through the items in your cart. and check if any other item has the same "Rope_ID" when removing an item. If found, you can remove those items as well.

a simple JS ex:

function removeFromCart(cart, itemId) {

  const updatedCart = cart.items.filter(item => {

    if (item.id === itemId) {

      // Check if thr r other items with the same Rope_ID

      const sameRopeIdItems = cart.items.filter(

        otherItem => otherItem.properties.Rope_ID === item.properties.Rope_ID

      );

      // Remove all the items with the same Rope_ID

      return sameRopeIdItems.every(

        sameRopeIdItem => sameRopeIdItem.id === itemId

      );

    }

    return true;

  });

  return { items: updatedCart };

}

// Example usage:

const cart = {

  items: [

    {

      id: 47172705059137,

      properties: {

        Rope_ID: "1699578662053"

      },

      quantity: 1,

      variant_id: 47172705059137,

      key: "47172705059137:78613041670c5e8886d92429b00d14cd",

    },

    {

      id: 46529331331393,

      properties: {

        End_1: "Splice Eyelet End w/-Thimble",

        End_2: "Heat Sealed Cut",

        Rope_ID: "1699578662053"

      },

      quantity: 1,

      variant_id: 46529331331393,

      key: "46529331331393:2f19286fc8bd365ed585af1c61c42815",

    }

  ]

};

const itemIdToRemove = 47172705059137;

const updatedCart = removeFromCart(cart, itemIdToRemove);

console.log(updatedCart);

This code defines a function removeFromCart that removes the specified item and all other items with the same "Rope_ID." The filter function is used to achieve this.