Skip to content Skip to sidebar Skip to footer

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 Mat

Solution 1:

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] ofObject.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);

Solution 2:

If you don't need to support ie directly you could use a combination of array.prototype.flatMap() and array.prototype.map().

let attributes = {
      color: ["Red", "Blue"],
      sizes: ["Small", "Medium", "Large"],
    };

    const combo = attributes.color.flatMap((d) =>
      attributes.sizes.map((v) => ({ color: d, sizes: v }))
    );

    console.log(combo);

A more generic solution which uses cartesian product of arrays in vanilla JS could look like this.

let attributes = {
    color: ['Red', 'Blue'],
    sizes: ['Small', 'Medium', 'Large'],
    material: ['Cotton', 'Wool']
  };

    constf = (a, b) => [].concat(...a.map(d => b.map(e => [].concat(d, e))));
    constcartesian = (a, b, ...c) => (b ? cartesian(f(a, b), ...c) : a);
  
  const resArr = cartesian(attributes.color, attributes.sizes, attributes.material);
   const resObj = resArr.map((x)=>({color:x[0], sizes:x[1], material: x[2]}))
  console.log(resObj);

Post a Comment for "Create Product Variants Based On Attributes"