根据属性创建产品变体



我正在制作一个电子商务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);

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

如果你不需要直接支持ie,你可以使用array.prototype.flatMap()和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);

一个更通用的解决方案,在香草JS中使用数组的笛卡尔积,可能是这样的:

let attributes = {
color: ['Red', 'Blue'],
sizes: ['Small', 'Medium', 'Large'],
material: ['Cotton', 'Wool']
};
const f = (a, b) => [].concat(...a.map(d => b.map(e => [].concat(d, e))));
const cartesian = (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);

最新更新