根据属性创建产品变体 [英] Create product variants based on attributes
本文介绍了根据属性创建产品变体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在开发一个电子商务javascript应用程序,并试图根据属性创建产品变体.
I am working on an eCommerce javascript app, and trying to create product variants based on attributes.
如果产品具有属性:
大小:小,中,大
颜色:红色,蓝色
材料:棉,羊毛
我想要这样的结果 [{颜色:红色",尺寸:小"},{颜色:蓝色",尺寸:小"},{颜色:红色";,尺寸:"Medium"},{颜色:"Blue",尺寸:"Medium"},{颜色:"Red",尺寸:"Large"},{color:"Blue",大小:大"}]
我已经做到了,但是有简单的方法吗?
I've done this, but is there an easy way to do this?
这是我已完成的代码:
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);
推荐答案
尝试一下:
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);
这篇关于根据属性创建产品变体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文