I’m working on a headless Shopify store using Gatsby, and am having some trouble building a robust product option picker.
I have an options
object that looks like this:
{
extras: "Pouch only",
}
The key and value will be different for every product, so I won’t know the values.
I have a variants
array that will have a key/value pair that matches this object. Here is the shape of the variants array:
[
{
extras: "Pouch only",
...otherValues,
},
{
extras: "Add tassel",
...otherValues,
},
{
extras: "Add charm",
...otherValues,
},
{
extras: "Add tassel & charm",
...otherValues,
},
{
sizes: "S",
...otherValues,
},
{
sizes: "M",
...otherValues,
},
{
sizes: "L",
...otherValues,
},
{
sizes: "XL",
...otherValues,
},
];
If I knew the name of the variant ahead of time, I could do something like this:
const newVariant = variants.find((v) => {
return v.extras === options.extras;
});
How can I do the same thing without knowing the name of the key?
4
Answers
Using
Object.entries
you can retrieve key/value pairs of the object, and check if.some
(or.every
depending on your needs) match:Take the entries of the
option
object and stringify them. Then, when searching through thevariants
, find (or filter) by the ones which have an entry matching the entry previously stringified:If you need every key-value pair in the
options
object to match, rather than just at least one to match, then change the.some
to.every
.You could make the function a bit more efficient by making a Set of the stringified entries instead of using an array:
You can loop through the object key for check. I think this solves your issue.
You can do this using
filter
and thensome
inside of it. Here is how:Also if you want search for all values in filter,
some
could be replaced withevery
method.