我正在创建电子商务仪表盘。仪表板的一部分是让用户能够创建产品的变体。到目前为止,这是我的想法:
const options = [
{
display_name: "Colour",
_id: "5e70047aa2f3c2574a27e4a2",
option_values: [
{
_id: "5e736980646ed90f741f1198",
label: "Red"
},
{
_id: "5e736980646ed90f741f1197",
label: "Green"
}
]
},
{
display_name: "Size",
_id: "5e70047aa2f3c2574a27e4a3",
option_values: [
{
_id: "5e736980646ed90f741f1199",
label: "Small"
},
{
_id: "5e736980646ed90f741f1121",
label: "Medium"
}
]
},
{
display_name: "Weight",
_id: "5e70047aa2f3c2574a27e4g3",
option_values: [
{
_id: "5e736980646ed90f741f1122",
label": "10"
}
]
}
]
用户最终创建了一个由3个对象组成的数组:颜色,大小,重量。每个对象中都有一个嵌套的数组,其中包含option_values。例如由“红色”和“绿色”组成。
现在要使其正常工作,我需要使用此选项数组并将其转换为如下所示的变体数组:
const variants = [
{
price: 0,
sku: "RED-SMALL-10",
option_values: [
{
option_id: "5e736980646ed90f741f1198",
id: "5e70047aa2f3c2574a27e4a2"
},
{
option_id: "5e736980646ed90f741f1199",
id: "5e70047aa2f3c2574a27e4a3"
},
{
option_id: "5e736980646ed90f741f1122",
id: "5e70047aa2f3c2574a27e4g3"
},
]
},
{
price: 0,
sku: "RED-MEDIUM-10",
option_values: [
{
option_id: "5e736980646ed90f741f1198",
id: "5e70047aa2f3c2574a27e4a2"
},
{
option_id: "5e736980646ed90f741f1121",
id: "5e70047aa2f3c2574a27e4a3"
},
{
option_id: "5e736980646ed90f741f1122",
id: "5e70047aa2f3c2574a27e4g3"
},
]
},
{
price: 0,
sku: "GREEN-SMALL-10",
option_values: [
{
option_id: "5e736980646ed90f741f1197",
id: "5e70047aa2f3c2574a27e4a2"
},
{
option_id: "5e736980646ed90f741f1199",
id: "5e70047aa2f3c2574a27e4a3"
},
{
option_id: "5e736980646ed90f741f1122",
id: "5e70047aa2f3c2574a27e4g3"
},
]
},
{
price: 0,
sku: "GREEN-SMALL-10",
option_values: [
{
option_id: "5e736980646ed90f741f1197",
id: "5e70047aa2f3c2574a27e4a2"
},
{
option_id: "5e736980646ed90f741f1121",
id: "5e70047aa2f3c2574a27e4a3"
},
{
option_id: "5e736980646ed90f741f1122",
id: "5e70047aa2f3c2574a27e4g3"
},
]
}
]
使用此数组,用户将能够看到包含以下内容的变体:
Red - Small - 10
Red - Medium - 10
Green - Small - 10
Green - Medium - 10
您可以想象,用户可以根据需要添加额外的权重,因此看起来像这样:
Red - Small - 10
Red - Small - 12
Red - Medium - 10
Red - Medium - 12
Green - Small - 10
Green - Small - 12
Green - Medium - 10
Green - Medium - 12
我遇到的问题是将options数组转换为Variants数组。谁能帮忙吗?
1)首先通过遍历选项来构建可能的组合sets
。2)用键作为idObj
的值构建_id
。3)从第1步中越过sets
并以所需形式构建每个对象。