Filter and Compare Arrays

Filter and Compare Arrays

I've been creating a ecommerce app with Gatsby + Shopify, and had to think a bit about handling product variants.

Shopify gives you a products variants as an array, with the variants option (I.e. Size: Large, Color: Green) in a field called selectedOptions:

{
    // ...
  "variants": [
    {
            // ...
      "selectedOptions": [
        {
          "name": "Size",
          "value": "Large"
        }
      ]
    },
    {
            // ...
      "selectedOptions": [
        {
          "name": "Size",
          "value": "Medium"
        }
      ]
    },
    {
            // ...
      "selectedOptions": [
        {
          "name": "Size",
          "value": "Small"
        }
      ]
    }
  ]
}

And in my variants form component, the currently selected options looked like this:

const selectedOptions = {
    'Size': 'Large'
}

So to find the matching variant - which I would then add to cart - I used this small bit of code:

const variants = product.variants
const matchedVariant = variants.find(variant =>
      variant.selectedOptions.every(
        ({ name, value }) => value === selectedOptions[name]
      )
    )
console.log(matchedVariant)
// Do something with matchedVariant

Address

Address?
Not happening.
I get enough email spam as it is ¯\_(ツ)_/¯