Create product variants based on attributes

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);

Answer

try this:

let attributes = {
  color: ['Red', 'Blue'],
  sizes: ['Small', 'Medium', 'Large'],
  material: ['Cotton', 'Wool'],
  gender: ['Men', 'Women'],
  type: ['Casual', 'Sport']
};


let attrs = [];

for (const [attr, values] of Object.entries(attributes))
  attrs.push(values.map(v => ({[attr]:v})));

attrs = attrs.reduce((a, b) => a.flatMap(d => b.map(e => ({...d, ...e}))));

console.log(attrs);

Leave a Reply

Your email address will not be published. Required fields are marked *