根据属性创建产品变体

Muh*_*een 1 javascript arrays object

我正在开发一个电子商务 JavaScript 应用程序,并尝试根据属性创建产品变体。

如果产品具有以下属性:

尺寸:小号、中号、大号

颜色:红色, 蓝色

材质:棉、羊毛

我想要这样的结果[{color: "Red", sizes: "Small"}, {color: "Blue", sizes: "Small"}, {color: "Red", sizes: "Medium"}, {color: "Blue", sizes: "Medium"}, {color: "Red", sizes: "Large"}, {color: "Blue", sizes: "Large"}]

我已经这样做了,但是有没有简单的方法可以做到这一点?

这是我完成的代码:

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);
Run Code Online (Sandbox Code Playgroud)

syd*_*uki 5

尝试这个:

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);
Run Code Online (Sandbox Code Playgroud)