Skip to content

Instantly share code, notes, and snippets.

@PavelJurasek
Created May 7, 2019 19:05
Show Gist options
  • Save PavelJurasek/29c9333d7f5b793a767771417b22f20e to your computer and use it in GitHub Desktop.
Save PavelJurasek/29c9333d7f5b793a767771417b22f20e to your computer and use it in GitHub Desktop.
Build variant slug from pattern
const Product = {
"attributes": [
{
"name": "Color",
"value": "red", // whatever
},
{
"name": "Size",
"value": 'M',
},
],
"pattern": "Color-Size",
}
buildSlug = (product) => {
pattern = product.pattern.split('-');
const parts = [];
const partCount = pattern.length;
for (let i = 0; i < partCount; i++) {
const partName = pattern[i];
const attrCount = product.attributes.length;
const attr = product.attributes.find(attr => attr.name === partName);
if (attr === undefined) {
throw "Attribute not found.";
}
parts.push(attr.value);
}
return parts.join('-');
};
console.log(buildSlug(Product));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment