Created
May 7, 2019 19:05
-
-
Save PavelJurasek/29c9333d7f5b793a767771417b22f20e to your computer and use it in GitHub Desktop.
Build variant slug from pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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