I am working on an eCommerce javascript app, and trying to create product variants based on attributes.
If a product has attributes:
Size: Small, Medium, Large
Color: Red, Blue
Material: Cotton, Wool
I want result like this [{color: "Red", sizes: "Small"}, {color: "Blue", sizes: "Small"}, {color: "Red", sizes: "Medium"}, {color: "Blue", sizes: "Medium"}, {color: "Red", sizes: "Large"}, {color: "Blue", sizes: "Large"}]
I've done this, but is there an easy way to do this?
Here is the code that I've done:
let attributes = {
color: ['Red', 'Blue'],
sizes: ['Small', 'Medium', 'Large'],
material: ['Cotton', 'Wool']
};
let getProducts = (arrays) => {
if (arrays.length === 0) {
return [[]];
}
let results = [];
getProducts(arrays.slice(1)).forEach((product) => {
arrays[0].forEach((value) => {
results.push([value].concat(product));
});
});
return results;
};
let getAllCombinations = (attributes) => {
let attributeNames = Object.keys(attributes);
// console.log(attributeNames);
let attributeValues = attributeNames.map((name) => attributes[name]);
// console.log(attributeValues);
return getProducts(attributeValues).map((product) => {
obj = {};
attributeNames.forEach((name, i) => {
obj[name] = product[i];
});
return obj;
});
};
let combinations = getAllCombinations(attributes);
console.log(combinations.length);
console.log(combinations);